Reputation: 3780
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)
Upvotes: 14
Views: 1060
Reputation: 120941
The difference is:
(1) The variable is initialized to the zero value for a slice, which is nil (foo == nil
).
(2) and (3) assign non-nil slices to the variable (foo != nil
). The slice's underlying array pointer is set to an address reserved for 0-byte allocations.
The following points are true for all three statements:
len(foo) == 0
.cap(foo) == 0
.Because len, cap and append work with nil slices, (1) can often be used interchangeably with (2) and (3).
Statements 2 and 3 are short variable declarations. These statements can also be written as a variable declaration with an initializer.
var foo = []int{}
var foo = make([]int, 0)
All of the options are used commonly in Go code.
Upvotes: 10