Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I define an empty slice in Go?

Tags:

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)
like image 922
Andrew C Avatar asked Jan 20 '15 18:01

Andrew C


People also ask

What defines an empty slice?

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.

Can a slice be nil in go?

The zero value of a slice is nil .

How do you empty a slice?

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).


1 Answers

The difference is:

  1. is a nil slice (foo == nil).
  2. and 3. are non-nil slices (foo != nil).

The following points are true for all three statements:

  • The statement does not allocate memory.
  • The slice length is zero: len(foo) == 0.
  • The slice capacity is zero: 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.

like image 154
Bayta Darell Avatar answered Oct 13 '22 07:10

Bayta Darell