Senior
String in Go — what is it, how is it organized under the hood?
sobes.tech AI
Answer from AI
In Go, a string (string) is an immutable sequence of bytes, typically representing text in UTF-8 encoding. Under the hood, a string is very simple: it is a structure with a pointer to a byte array and a length.
Typically, a string in Go looks like:
// simplified
type stringHeader struct {
Data uintptr // pointer to data
Len int // length in bytes
}
Because of immutability, any operations that modify a string create a new byte array. This allows efficient passing of strings by value without copying data — only the pointer and length are copied.
Important:
- A string stores bytes, not Unicode characters. To work with characters (runes), you should use the
unicode/utf8package. - Due to UTF-8, characters can occupy a different number of bytes.
Example:
s := "Привет"
fmt.Println(len(s)) // number of bytes
for i, r := range s {
fmt.Printf("%d: %c\n", i, r) // i — byte index, r — rune
}