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)
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)
1) is a nil slice.
2) and 3) are non-nil slices with length zero and capacity zero.
None of the options allocate memory.
All of the options are used commonly in Go code.
Because len
, cap
and append
work with nil slices, 1) can often be used interchangeably with 2) and 3).