For Golang developers, it is very common to use append function to append new elements into slice. The common syntax is like below:
var slice := make([]int, 0)
slice = append(slice, 123)
And for some requirements, you may want to create a new slice based on an existing slice. We know the below the code will work perfectly. slice := []int{1,2,3}
newSlice := make([]int, 0)
newSlice = append(newSlice, append(slice, 4)...)
Below is complete example code to show the result:package main
import (
"fmt"
)
func main() {
// here create the origin slice with cap 10 to make sure that
// the slice is big enough to hold more data
slice := make([]int, 0, 10)
slice = append(slice, []int{1, 2, 3}...)
newSlice := make([]int, 0)
newSlice = append(newSlice, append(slice, 4)...)
fmt.Println(slice)
fmt.Println(newSlice)
fmt.Printf("The address of slice: %v\n", &slice[0])
fmt.Printf("The address of newSlice: %v\n", &newSlice[0])
}
The result is:[1 2 3]
[1 2 3 4]
The address of slice: 0xc000014050
The address of newSlice: 0xc00007a000
You can see the two slices have different addresses. slice := []int{1,2,3}
newSlice := make([]int, 0)
newSlice = append(slice, 4)package main
import (
"fmt"
)
func main() {
// here create the origin slice with cap 10 to make sure that
// the slice is big enough to hold more data
slice := make([]int, 0, 10)
slice = append(slice, []int{1, 2, 3}...)
newSlice := make([]int, 0)
newSlice = append(slice, 4)
fmt.Println(slice)
fmt.Println(newSlice)
fmt.Printf("The address of slice: %v\n", &slice[0])
fmt.Printf("The address of newSlice: %v\n", &newSlice[0])
}[1 2 3]
[1 2 3 4]
The address of slice: 0xc00010a000
The address of newSlice: 0xc00010a000
See newSlice is pointing to the same address of slice? slice := []int{1,2,3}
newSlice := make([]int, 0)
newSlice = append(newSlice, append(slice, 4)...) slice := []int{1,2,3}
newSlice := make([]int, 0)
newSlice = append(newSlice, slice...)
newSlice = append(newSlice, 4)