Junior — Middle
How is the internal structure of the string type organized in the Go language?
sobes.tech AI
Answer from AI
In the Go language, a string (string) is an immutable data type that represents a sequence of bytes in UTF-8 encoding. Internally, a string is implemented as a structure with two fields:
- a pointer to a byte array (a slice of bytes) where the string content is stored;
- the length of the string (number of bytes).
This can be roughly represented as:
// simplified representation of the internal string structure
type stringStruct struct {
ptr *byte // pointer to data
len int // length in bytes
}
Because strings are immutable, any modification creates a new copy of the data. This ensures safety and simplicity when working with strings but requires attention during frequent concatenations (it's better to use strings.Builder).
Also, note that the length is stored in bytes, not in Unicode characters, so to work with characters, you should use the unicode/utf8 package.