I am currently reading the Go Programming Language book which describes that a copy of a string or a substring has similar memory addresses.
s := "hello"
c := s
fmt.Println(&s, &c) // prints 0xc000010230 0xc000010240
My question is, shouldn't &c be the same as &s since it c is an exact copy ?
RAM
Address | Value
&s 0xc000010230 | "hello" <----- s
&c 0xc000010240 | "hello" <----- c
CodePudding user response:
c and s are actually two distinct string headers. But both of them point to the same "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
The Data field of the string header points to the first byte in the string and the Len field of the string header indicates the length of the string. You can use that information to confirm that the string header is pointing to the original string.
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)
}
