In this example, we will show you how to use built-in append function appends new elements to the slice in Go with an example.
Go slice append - The built-in append function appends new elements to the slice.
Go - slice append example
In the example, we append new elements to a slice, which already has two elements.
package main
import "fmt"
func main() {
vals := make([]int, 2)
fmt.Printf("slice: %v; len: %d; cap: %d \n", vals, len(vals), cap(vals))
fmt.Println("---------------------------")
vals = append(vals, 10)
vals = append(vals, 20)
vals = append(vals, 30)
vals = append(vals, 40, 50, 60)
fmt.Printf("slice: %v; len: %d; cap: %d \n", vals, len(vals), cap(vals))
}
Output:
slice: [0 0]; len: 2; cap: 2 --------------------------- slice: [0 0 10 20 30 40 50 60]; len: 8; cap: 8
Comments
Post a Comment