The zero value of a slice is not nil

后端 未结 1 885
独厮守ぢ
独厮守ぢ 2021-02-13 01:37

I was following the example https://tour.golang.org/moretypes/10 I modified the code expecting to get the same result. I did not. Is this a bug, or a documentation error? The to

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-13 01:40

    The doc you referenced states that a nil slice has a length and capacity of 0, but not that every slice of length and capacity of zero is a nil slice. The specification only says that the value of an uninitialized slice is nil.

    This is a convenience to support len and cap on slices which are uninitialised (nil). Otherwise we would need to check for non-nil first in order to avoid panic. (This also holds for other in-built types like maps or channels.)

    In terms of the fmt.Print output, the difference in behaviour is similar to printing an uninitialised (nil) pointer vs pointer to an empty structure:

    var s *struct{} // uninitialised pointer
    fmt.Println(s)  // 
    
    s = &struct{}{} // pointer to an empty structure
    fmt.Println(s)  // &{}
    

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