'Why does a slice expression of an empty slice have values in it?
Just started leaning Golang. Facing some trouble understanding the slice expression.
package main
import "fmt"
func main() {
x := make([]int, 0, 5)
y := append(x, 20)
fmt.Println(x, y, x[:2], y[:2])
}
Output:
[] [20] [20 0] [20 0]
Here's my understanding of what this represents:
x := make([]int, 0, 5)- make a new slice of ints with 0 length and 5 capacity.y := append(x, 20)- create a a new slice using append function with length 1 & capacity of 5.yis[20].fmt.Println(x, y, x[:2], y[:2])- How does
x[:2]print[20 0]? Shouldn't it just cause an error? If this was the slice expression creating a new slice shouldn't it be[0 0]? How is the first value 20?
- How does
I am missing some fundamental concept here.
If I were to take a guess I think creating y using y := append(x, 20) is somehow sharing the underlying memory. This is not shown when I print x directly, but when I am printing x[:2] it is shown.
Solution 1:[1]
y := append(x, 20) - create a a new slice using append function with length 1 & capacity of 5. y is [20].
Not true. Because there is capacity already available, it does not allocate a new array. That is the whole point of pre-allocating a slice with capacity greater than its length.
x := make([]int, 0, 5)
Yields a slice [] over an array [0, 0, 0, 0, 0].
y := append(x, 20)
Yields a slice [20] over the same array, now [20, 0, 0, 0, 0].
fmt.Println(x, y, x[:2], y[:2])
Produces four slices:
x = [] // (its length & cap haven't changed)
y = [20] // (see append explanation above)
x[:2] = [20, 0] // (first two elements of the underlying array)
y[:2] = [20, 0] // (same two elements of the same array)
This is covered in detail in the Tour of Go and in further detail on the Go blog.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
