Senior
How is the string implemented under the hood in Go?
sobes.tech AI
Answer from AI
In Go, a string (string) is an immutable byte slice, which is internally represented by a structure with two fields:
- a pointer to a byte array,
- the length of the string.
That is, a string is simply a pointer to a sequence of bytes and its length. Memory for the bytes is allocated separately and is not copied when passing the string, making operations with them efficient.
An example of the internal representation (simplified):
// Internally, string is similar to:
type stringHeader struct {
Data uintptr // pointer to bytes
Len int // length of the string
}
Due to the immutability of strings, any operations that modify the content create a new byte array and a new string.