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
+6.9k Default cipher that OpenSSL used to encrypt a PEM file
+13.2k Golang : How to get a user home directory path?
+6.4k Golang : Test input string for unicode example
+5k JQuery : Calling a function inside Jquery(document) block
+18.7k Golang : Find IP address from string
+7.4k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+8.3k Swift : Convert (cast) Character to Integer?
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+12.1k Golang : Sort and reverse sort a slice of runes
+38.1k Golang : Read a text file and replace certain words
+7.7k Golang : get the current working directory of a running program