golang中的数组与切片

来源:互联网 发布:如何强身健体知乎 编辑:程序博客网 时间:2024/05/20 02:55

golang中,当用数组去初始化一个切片时,数组的地址即为&slice[0],例子如下:

package mainimport ("fmt""math/rand""net""os""time""unsafe")func main() {for {pcRecvMag()time.Sleep(time.Second)}}func pcRecvMag() {var buf [20]bytereadFromUDP(buf[0:])pcHandleMsg(&buf)}func pcHandleMsg(p2byteArray *[20]byte) {fmt.Printf("byteArray pointer:%v\n", unsafe.Pointer(p2byteArray))fmt.Println(*p2byteArray)}func readFromUDP(b []byte) {b[0] = (byte)(rand.Intn(255))b[1] = (byte)(rand.Intn(255))fmt.Printf("len:%d, cap:%d\n", len(b), cap(b))fmt.Printf("slice0 pointer:%v\n", &b[0])}
输出结果:

len:20, cap:20

slice0 pointer:0x115ad940

byteArray pointer:0x115ad940

[86 132 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

len:20, cap:20

slice0 pointer:0x1157a340

byteArray pointer:0x1157a340

[122 254 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

len:20, cap:20

slice0 pointer:0x115ad9e0

byteArray pointer:0x115ad9e0

[151 153 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]


这一点可以用slice的数据结构来解释,如下图所示:

这个是 slice 的数据结构,它很简单,一个指向真实 array 地址的指针 ptr ,slice 的长度 len 和容量 cap 。




原创粉丝点击