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
+33.5k Golang : convert(cast) bytes to string
+14.2k Golang : How to filter a map's elements for faster lookup
+6.7k Golang : How to call function inside template with template.FuncMap
+12k Golang : 2 dimensional array example
+5.5k Golang : Error handling methods
+7.6k Golang : Ways to recover memory during run time.
+23.5k Golang : Fix type interface{} has no field or no methods and type assertions example
+8.2k Golang : Ackermann function example
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+6.5k Golang : Output or print out JSON stream/encoded data
+8k Prevent Write failed: Broken pipe problem during ssh session with screen command
+6k Golang : Process non-XML/JSON formatted ASCII text file example