3

slice 自身的指针为什么会变

 2 years ago
source link: https://studygolang.com/articles/35063
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

slice 自身的指针为什么会变

Agzer0 · 1天之前 · 87 次点击 · 预计阅读时间不到 1 分钟 · 大约8小时之前 开始浏览    

今天在学习unsafe.Pointer用法的时候,无意中发现这么写slice自身的指针会变

    data := []byte{0, 0}
    fmt.Printf("%p\n", data) // 0xc0001202a0
    p := (*[2]byte)(unsafe.Pointer(&data))
//    p := (*[2]byte)(unsafe.Pointer(&data[0])) // 如果换成这种写法,则没问题
    fmt.Printf("%p\n", data) // 0xc0001202a0

    for i := range p {
        p[i] = 1
        // fmt.Printf("%p\n", data) 在这里每次循环,data的指针都会改变
    }
    fmt.Printf("%p\n", data) // 0xc000120101

有没有大佬知道这是什么原因吗


有疑问加站长微信联系(非本文作者))

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK