我目前正在閱讀 Go 編程語言書,該書描述了字串或子字串的副本具有相似的記憶體地址。
s := "hello"
c := s
fmt.Println(&s, &c) // prints 0xc000010230 0xc000010240
我的問題是,不應該&c和&s因為它c是一個精確的副本一樣嗎?
RAM
Address | Value
&s 0xc000010230 | "hello" <----- s
&c 0xc000010240 | "hello" <----- c
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422093.html
標籤:
