Senior
a := []int{1} // *T &1111000 len cap fmt.Println(len(a), cap(a)) // 1 1 b := append(a, 2) // *T &1111001 fmt.Println(len(b), cap(b)) // 2 2 b[0] = 0 fmt.Println(a) // [1] fmt.Println(b) // [1 2] c := append(b, 3) // [1 2 3] len = 3, cap = 4 // *T &1111011 ? d := append(c, 4) // [1 2 3 4] // len = 4, cap = 4 // *T &1111011 ? c[0] = 100 fmt.Println(b) // fmt.Println(c) // fmt.Println(d) //
sobes.tech AI
Answer from AI
In Go, slices (slice) are a structure that contains a pointer to an array, a length, and a capacity. When using append, the behavior depends on the current capacity of the slice.
Let's analyze an example:
package main
import "fmt"
func main() {
a := []int{1} // len=1, cap=1
fmt.Println(len(a), cap(a)) // 1 1
b := append(a, 2) // len=2, cap=2, a new array is allocated
fmt.Println(len(b), cap(b)) // 2 2
b[0] = 0
fmt.Println(a) // [1] - a did not change because b points to a new array
fmt.Println(b) // [0 2]
c := append(b, 3) // len=3, cap=4, capacity increased, new array
d := append(c, 4) // len=4, cap=4, capacity did not change, same array
c[0] = 100
fmt.Println(b) // [0 2] - b and c point to different arrays
fmt.Println(c) // [100 2 3 4]
fmt.Println(d) // [100 2 3 4] - d and c point to the same array
}
Explanation:
- When
appendis called and the slice's capacity is insufficient, a new array is allocated, and data is copied. - If the capacity allows,
appendmodifies the existing array. - In the example, after the first
append,bpoints to a new array, so changingb[0]does not affecta. - When appending to
c, the capacity increased, and a new array was allocated. - When appending to
d, the capacity was sufficient, socanddpoint to the same array, and changingc[0]is visible ind.
Thus, it is important to understand that slices may share or not share the underlying array depending on capacity and append operations.