Declare slice or make slice?

前端 未结 4 464
情书的邮戳
情书的邮戳 2020-12-12 13:14

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?

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 13:15

    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.

提交回复
热议问题