Declare slice or make slice?

前端 未结 4 472
情书的邮戳
情书的邮戳 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:16

    A bit more completely (one more argument in make) example:

    slice := make([]int, 2, 5)
    fmt.Printf("length:  %d - capacity %d - content:  %d", len(slice), cap(slice), slice)
    

    Out:

    length:  2 - capacity 5 - content:  [0 0]
    

    Or with dynamic type of slice:

    slice := make([]interface{}, 2, 5)
    fmt.Printf("length:  %d - capacity %d - content:  %d", len(slice), cap(slice), slice)
    

    Out:

    length:  2 - capacity 5 - content:  [ ]
    

提交回复
热议问题