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
+10.4k Elastic Search : Return all records (higher than default 10)
+14.4k Golang : Capture stdout of a child process and act according to the result
+5.4k Golang : Array mapping with Interface
+3.9k Golang : Issue HTTP commands to server and port example
+6.3k Golang : Get today's weekday name and calculate target day distance example
+8.5k Golang : How to delete element(data) from map ?
+6.7k Golang : How To Use Panic and Recover
+4.2k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+3.9k Javascript : How to loop over and parse JSON data?
+12.2k Golang : On enumeration
+14.4k Golang : Get file permission
+16.2k Golang : Get host name or domain name from IP address