Andrew C
Andrew C

Reputation: 3780

How should I define an empty slice in Go?

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?

  1. var foo []int
  2. foo := []int{}
  3. foo := make([]int, 0)

Upvotes: 14

Views: 1060

Answers (1)

Thundercat
Thundercat

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:

  • The slice length is zero: len(foo) == 0.
  • The slice capacity is zero: cap(foo) == 0.
  • The statement does not allocate memory.

Playground example

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.

  1. var foo = []int{}
  2. var foo = make([]int, 0)

All of the options are used commonly in Go code.

Upvotes: 10

Related Questions