我目前正在閱讀 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 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消