Reputation: 183
What is the point of differentiating between a nil slice, ie. uninitialized slice, and an empty slice, ie. initialized but empty slice?
I understand the difference, but I'm wondering what the motivation is behind having the subtle difference between the two cases? For all intents and purposes, a nil slice and an empty slice behave the same when using them.
It seems as though if Go developers just had one case, for example only allowed empty slices, it would have simplified the mental model and eliminated sources of subtle bugs.
Is there a reason why those two use cases were created?
Upvotes: 6
Views: 4927
Reputation: 417512
A nil
slice value needs no allocation. That might make a difference in cases where you want to build something in a slice, but often there will be no data to be appended, so the slice may remain nil
, so no allocation will be required altogether.
An empty slice might require an allocation, even if its capacity is zero.
Also an empty slice means its length is 0, but its capacity may not be; so it's not true that "For all intents and purposes, a nil
slice and an empty slice behave the same when using them.". You can allocate a slice with 0 length and a big capacity, optimizing for further appends to avoid allocations (and copying over):
s := make([]int, 0)
fmt.Println(s, len(s), cap(s))
s = append(s, 1)
fmt.Println(s, len(s), cap(s))
s = make([]int, 0, 10)
fmt.Println(s, len(s), cap(s))
s = append(s, 1)
fmt.Println(s, len(s), cap(s))
Output of the above (try it on the Go Playground):
[] 0 0
[1] 1 2
[] 0 10
[1] 1 10
What do we see? In the first example we created an empty slice with 0 length and 0 capacity. If we append an element to it, its length will become 1 (obviously), and its capacity increased to 2. This is because under the hood append()
allocated a new array with size of 2 (thinking of future growth), copied the existing elements over (which was none in this case), and assigned the new element.
In the second case we started with an empty slice but with a capacity of 10. This means we can append 10 elements to it without causing a new allocation and copying existing elements. This can be a big plus when slices are big and this needs to be done many times.
Upvotes: 6