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
+11.7k Golang : Convert IPv4 address to packed 32-bit binary format
+5.6k Golang : Humanize and Titleize functions
+12.5k Golang : Tutorial on loading GOB and PEM files
+7.3k Swift : Convert (cast) Character to Integer?
+9k Android Studio : Simple input textbox and intercept key example
+8k Golang : Go as a script or running go with shebang/hashbang style
+5.9k Golang : How to call function inside template with template.FuncMap
+6.3k Golang : Create zip/ePub file without compression(use Store algorithm)
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+8.6k Golang : Resumable upload to Google Drive(RESTful) example
+5.2k Golang & Javascript : How to save cropped image to file on server
+10.8k Golang : Convert a rune to unicode style string \u