Why are strings in Go immutable, and what is the relationship between a string and a []byte?
Last updated
A string is an immutable pointer-plus-length over bytes, so it can be shared cheaply, used as a map key, and passed across goroutines without locking.
A
[]byteis the mutable counterpart, and conversionsstring(b)/[]byte(s)copy the data. Indexing a string gives bytes, whilerangeyields decodedrunes.For heavy concatenation use
strings.Builderor a[]byteto avoid repeated allocations.