Declare slice or make slice?

前端 未结 4 461
情书的邮戳
情书的邮戳 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.

    0 讨论(0)
  • 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:  [<nil> <nil>]
    
    0 讨论(0)
  • 2020-12-12 13:19

    Just found a difference. If you use

    var list []MyObjects
    

    and then you encode the output as JSON, you get null.

    list := make([]MyObjects, 0)
    

    results in [] as expected.

    0 讨论(0)
  • 2020-12-12 13:29

    In addition to fabriziom's answer, you can see more examples at "Go Slices: usage and internals", where a use for []int is mentioned:

    Since the zero value of a slice (nil) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop:

    // Filter returns a new slice holding only
    // the elements of s that satisfy f()
    func Filter(s []int, fn func(int) bool) []int {
        var p []int // == nil
        for _, v := range s {
            if fn(v) {
                p = append(p, v)
            }
        }
        return p
    }
    

    It means that, to append to a slice, you don't have to allocate memory first: the nil slice p int[] is enough as a slice to add to.

    0 讨论(0)
提交回复
热议问题