Golang : Append and add item in slice
Problem :
You need to append/add new element into a existing slice. How to do that?
Solution :
Use the builtin function append()
. For example :
package main
import (
"fmt"
)
var a = make([]int, 8)
func AddElement(slice []int) []int {
newSlice := append(slice, 8) //<--- here!
return newSlice
}
func main() {
for i := 0; i < 8; i++ {
a[i] = i
}
fmt.Println("Before :", a)
newa := AddElement(a)
fmt.Println("After :", newa)
}
Output :
Before : [0 1 2 3 4 5 6 7]
After : [0 1 2 3 4 5 6 7 8]
See also : Golang : How to get capacity of a slice or array?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.5k Linux : How to fix Brother HL-1110 printing blank page problem
+24.6k Golang : GORM read from database example
+27.6k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+25.7k Golang : convert rune to integer value
+6.9k Golang : Get expvar(export variables) to work with multiplexer
+19.3k Golang : Delete item from slice based on index/key position
+13.9k Golang : unknown escape sequence error
+5.5k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+12.8k Golang : Remove or trim extra comma from CSV
+20.3k Golang : Compare floating-point numbers
+6.3k Apt-get to install and uninstall Golang
+5.2k Golang : Check if a word is countable or not