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
+27.1k Golang : Find files by name - cross platform example
+6.5k PHP : Shuffle to display different content or advertisement
+11.5k Golang : Fuzzy string search or approximate string matching example
+24.4k Golang : Change file read or write permission example
+32.9k Golang : How to check if a date is within certain range?
+13.5k Golang : Qt progress dialog example
+7.2k Golang : Of hash table and hash map
+7.4k Golang : Get YouTube playlist
+37.4k Upload multiple files with Go
+11.6k How to tell if a binary(executable) file or web application is built with Golang?
+6.9k Golang : How to setup a disk space used monitoring service with Telegram bot
+15.4k Golang : invalid character ',' looking for beginning of value