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 Golang: Prevent over writing file with md5 hash
+10.5k Golang : Get UDP client IP address and differentiate clients by port number
+24.9k Golang : Convert long hexadecimal with strconv.ParseUint example
+7k Golang : Not able to grep log.Println() output
+26.4k Golang : How to check if a connection to database is still alive ?
+6.2k Golang : Calculate diameter, circumference, area, sphere surface and volume
+8.5k Golang : Heap sort example
+5.3k Python : Print unicode escape characters and string
+19.1k Golang : Get current URL example
+8.9k Golang : Write multiple lines or divide string into multiple lines
+7.9k Golang : Reverse text lines or flip line order example