Correct way to initialize empty slice

前端 未结 4 1011
春和景丽
春和景丽 2020-12-04 05:50

To declare an empty slice, with a non-fixed size, is it better to do:

mySlice1 := make([]int, 0)

or:

mySlice2 := []int{}
         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 06:16

    Empty slice and nil slice are initialized differently in Go:

    var nilSlice []int 
    emptySlice1 := make([]int, 0)
    emptySlice2 := []int{}
    
    fmt.Println(nilSlice == nil)    // true
    fmt.Println(emptySlice1 == nil) // false
    fmt.Println(emptySlice2 == nil) // false
    

    As for all three slices, len and cap are 0.

提交回复
热议问题