In Golang, what is the difference between var s []int
and s := make([]int, 0)
?
I find that both works, but which one is better?
In Golang, what is the difference between var s []int
and s := make([]int, 0)
?
I find that both works, but which one is better?
In addition to fabriziom's answer, you can see more examples at "Go Slices: usage and internals", where a use for
[]int
is mentioned:It means that, to append to a slice, you don't have to allocate memory first: the
nil
slicep int[]
is enough as a slice to add to.Simple declaration
does not allocate memory and
s
points tonil
, whileallocates 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.
A bit more completely (one more argument in
make
) example:Out:
Or with dynamic type of
slice
:Out: