The anatomy of string

I’m trying to study the anatomy of string. Here’s the code:

str := "hello"
hdr := (*reflect.StringHeader)(unsafe.Pointer(&str))
dataPtr := hdr.Data
data := (*[5]int)(unsafe.Pointer(dataPtr))
fmt.Printf("data  \ntype: %T\nval: %#v\n\n", data, data)

And the output is:

data
type: *[5]int
val: &[5]int{8389759083119142248, 7580177697979577905, 7022364627547092078, 7166180736551186548, 8098991021358085729}

So my question is, what does these integers in the [5]int array represent?
Are they memory address of each characters?
If yes, how can we dereference them?

1 Like

You are unsafely pretending that the underlying array of type string is int. It is not. It is byte (uint8).

package main

import (
	"fmt"
	"reflect"
	"unsafe"
)

func main() {
	str := "hello"
	hdr := (*reflect.StringHeader)(unsafe.Pointer(&str))
	dataPtr := hdr.Data
	data := (*[1 << 20]byte)(unsafe.Pointer(dataPtr))[:len(str):len(str)]
	fmt.Printf("data  \ntype: %T\nval: %#v %q\n\n", data, data, data)
}

.

data  
type: []uint8
val: []byte{0x68, 0x65, 0x6c, 0x6c, 0x6f} "hello"

.

The Go Blog: Strings, bytes, runes and characters in Go

1 Like

I’m so so embarrassed that I asked this kind of stupid question. :persevere:
Thanks for your answer and the blog that you shared.

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