Or more precisely, it seems like I could do any of these three things. Is there any difference between them? Which is the best and why?
var foo []int
foo := []int{}
foo := make([]int, 0)
An empty slice is one that contains zero elements. It has an underlying array, but with zero elements. An empty slice is handy for representing an empty collection, such as when a query yields no results.
The zero value of a slice is nil .
To remove all elements, simply set the slice to nil . This will release the underlying array to the garbage collector (assuming there are no other references).
The difference is:
foo == nil
).foo != nil
).The following points are true for all three statements:
len(foo) == 0
.cap(foo) == 0
.Playground example
Because len, cap and append work with nil slices, (1) can often be used interchangeably with (2) and (3).
All of the options are used commonly in Go code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With