我目前正在阅读 Go 编程语言书,该书描述了字符串或子字符串的副本具有相似的内存地址。s := "hello"c := sfmt.Println(&s, &c) // prints 0xc000010230 0xc000010240我的问题是,不应该&c和&s因为它c是一个精确的副本一样吗? RAM Address | Value &s 0xc000010230 | "hello" <----- s &c 0xc000010240 | "hello" <----- c
1 回答

噜噜哒
TA贡献1784条经验 获得超7个赞
c并且s实际上是两个不同的字符串标题。但他们都指向同一个"hello"。
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
ch := (*reflect.StringHeader)(unsafe.Pointer(&c))
fmt.Println(sh.Data, ch.Data)
https://go.dev/play/p/Ckl0P3g4nVo
字符串头的Data字段指向字符串中的第一个byte,字符串头的Len字段表示字符串的长度。您可以使用该信息来确认字符串标头是否指向原始字符串。
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
for i := 0; i < sh.Len; i++ {
sp := (*byte)(unsafe.Pointer(sh.Data + uintptr(i)))
fmt.Printf("%p = %c\n", sp, *sp)
}
https://go.dev/play/p/LFfdxxARw1f
- 1 回答
- 0 关注
- 132 浏览
添加回答
举报
0/150
提交
取消