Declare slice or make slice?

Wang Yi picture Wang Yi · Aug 28, 2014 · Viewed 61k times · Source

In Go, what is the difference between var s []int and s := make([]int, 0)?

I find that both works, but which one is better?

Answer

fabrizioM picture fabrizioM · Aug 28, 2014

Simple declaration

var s []int

does not allocate memory and s points to nil, while

s := make([]int, 0)

allocates memory and s points to memory to a slice with 0 elements.

Usually, the first one is more idiomatic if you don't know the exact size of your use case.