Correct way to initialize empty slice

前端 未结 4 1006
春和景丽
春和景丽 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条回答
  •  爱一瞬间的悲伤
    2020-12-04 06:33

    They are equivalent. See this code:

    mySlice1 := make([]int, 0)
    mySlice2 := []int{}
    fmt.Println("mySlice1", cap(mySlice1))
    fmt.Println("mySlice2", cap(mySlice2))
    

    Output:

    mySlice1 0
    mySlice2 0
    

    Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

    See similar questions:

    What is the point of having nil slice and empty slice in golang?

    nil slices vs non-nil slices vs empty slices in Go language

提交回复
热议问题