What will this code print (garbage value converted to string)?

	s := make([]int, 500)
for i := range s {
	s[i] = i

v := unsafe.Pointer(&s)
v2 := (*string)(v)

fmt.Println("v:", v)
fmt.Println("v2:", v2)
fmt.Println("*v2:", *v2)

So, when converting this unsafe.Pointer to a string, am I correct in believing that whatever happens to be in memory at that location will be interpreted as:
first 8 bytes: a pointer to the string characters (produced by the size value of my s slice, namely value 500)
next 8 bytes the length of my string (produce by the capacity value or my slice, namely 500 in this example)

When I print this string value, why does it not show me the 500 runes (whatever was inmemory converted to runes) starting at address 500 in my program’s virtual address space ?

A string is not a sequence of runes, it’s a sequence of bytes. Your bytes contain a lot of nulls and control characters which might confuse you when looking at the printed output in a terminal. (Printing with fmt.Printf(“%x\n”, ...) might clarify.) Otherwise I think you have understood the mechanism of the unsafe conversion about right.

And there is of course no guarantee that the memory layout of []int and string have these similarities in general, but in the current go implementation that is the case.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.