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
+9.5k Golang : Populate slice with sequential integers example
+7.7k Golang Hello World Example
+9.3k Golang : Changing a RGBA image number of channels with OpenCV
+13.3k Golang : Strings comparison
+4.3k Java : Generate multiplication table example
+11.4k SSL : The certificate is not trusted because no issuer chain was provided
+11.7k Golang : Determine if time variables have same calendar day
+8.2k Golang : How to check if input string is a word?
+8k Golang : Metaprogramming example of wrapping a function
+5.5k List of Golang XML tutorials
+22.4k Golang : Strings to lowercase and uppercase example
+26.5k Golang : How to check if a connection to database is still alive ?