table of Contents
Add multiple elements to the slice
Whether the new slice returned by append and the original slice point to the same memory address
description
The append function is a built-in function of Go, which can dynamically add elements to the slice. The append function returns the added slice.
Syntax and parameters
Function signature
func append(slice []Type, elems ...Type) []Type
parameter name | meaning |
slice | The slice of the element to be added |
elems | Element to be added |
The append function allows multiple values to be added at once.
Usage example
Add elements to the slice
package main
import "fmt"
func main() {
demo := make([]int, 0, 1)
demo = append(demo, 1)
fmt.Println("demo:", demo)
// outputs: demo: [1]
}
Add multiple elements to the slice
package main
import "fmt"
func main() {
demo := make([]int, 0, 1)
demo = append(demo, 1, 3, 5)
fmt.Println("demo:", demo)
// outputs: demo: [1 3 5]
}
Combine other slices
With the append function, one slice can be merged into another slice:
package main
import "fmt"
func main() {
s1 := []int{23, 26, 28}
s2 := []int{3, 6, 9}
s1 = append(s1, s2...)
fmt.Println(s1)
// output: [23 26 28 3 6 9]
}
Precautions
Whether the new slice returned by append and the original slice point to the same memory address
According to the nature of the slice, when the append function is used to add elements to the slice, and the length of the slice does not exceed the cap before append, the slice will not expand, so the slice returned by append points to the same memory address as the original slice. On the contrary, append returns the expanded slice, which is different from the memory address of the original slice:
package main
import "fmt"
func main() {
source := make([]int, 0, 3)
fmt.Printf("source address: %p\n", source)
// output: source address: 0xc0000b6020
source = append(source, 1)
fmt.Printf("source address: %p\n", source)
// output: source address: 0xc0000b6020
source = append(source, 2, 3)
fmt.Printf("source address: %p\n", source)
// output: source address: 0xc0000ba000
}