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.4k Golang : get the current working directory of a running program
+7.1k Golang : Executing and evaluating nested loop in html template
+18k Golang : How to count the number of repeated characters in a string?
+11.1k Golang : Transform comma separated string to slice example
+7.7k Golang : Create and shuffle deck of cards example
+11.8k Golang : Fix image: unknown format error
+5.1k Nginx : Password protect a directory/folder
+5.8k Nginx : How to block user agent ?
+21.9k Golang : convert rune to integer value
+9.1k Golang : Command line file upload program to server example
+4.4k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+9.5k Golang : GTK Input dialog box examples