字符串复制内存地址的Golang内存分配
Golang memory allocation for string copy memory addresses
我目前正在阅读 Go Programming Language 一书,其中描述了字符串或子字符串的副本具有相似的内存地址。
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
c
和s
其实是两个distinct串headers。但是他们都指向同一个 "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
字符串header的Data
字段指向字符串中的第一个byte
,字符串header的Len
字段表示字符串的长度。您可以使用该信息来确认字符串 header 指向原始字符串。
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)
}
我目前正在阅读 Go Programming Language 一书,其中描述了字符串或子字符串的副本具有相似的内存地址。
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
c
和s
其实是两个distinct串headers。但是他们都指向同一个 "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
字符串header的Data
字段指向字符串中的第一个byte
,字符串header的Len
字段表示字符串的长度。您可以使用该信息来确认字符串 header 指向原始字符串。
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)
}