How can a slice contain itself?

后端 未结 3 1198
花落未央
花落未央 2020-11-30 06:12

I\'m trying to learn Golang using \"The Go Programming Language\" and I\'ve reached the section on slices. They make the comparison between arrays and slices in that two arr

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 06:42

    The below example creates a slice that contains itself:

    type Foo []Foo  
    bar := make(Foo, 1)
    bar[0] = bar
    

    This can be done because the slice value internally contains a pointer to an array, a length, and a capacity.

    An array on the other hand is a value. It can, at best, contain pointers to itself.

提交回复
热议问题