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
+19k Golang : Implement getters and setters
+12.1k Golang : GTK Input dialog box examples
+9k Yum Error: no such table: packages
+14.2k Golang : convert rune to unicode hexadecimal value and back to rune character
+11.9k Golang : How to detect a server/machine network interface capabilities?
+19.1k Golang : How to make function callback or pass value from function as parameter?
+15.4k Golang : Get HTTP protocol version example
+15.4k Golang : Get timezone offset from date or timestamp
+7.6k Golang : Process json data with Jason package
+11.7k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+12.1k Golang : Convert(cast) bigint to string
+9k Golang : Take screen shot of browser with JQuery example