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
+8.1k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+13.5k Golang : Parsing or breaking down URL
+9.8k Golang : Bubble sort example
+4.1k Fix Google Analytics Redundant Hostnames problem
+5.1k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+4.9k Swift : Get substring with rangeOfString() function example
+8.1k Golang : Populate or initialize struct with values example
+15.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+9.1k Golang : Check a web page existence with HEAD request example
+18.1k Golang : Clearing slice
+4.6k Swift : Convert string array to array example
+5k Golang : Find change in a combination of coins example