Junior — Middle
How is memory allocation and management handled when concatenating two strings in programming?
sobes.tech AI
Answer from AI
In Go, strings are immutable. When concatenating two strings, a new string is created, a new block of memory is allocated to hold the result, and characters from both source strings are copied.
Example:
s1 := "Hello, "
s2 := "world!"
s3 := s1 + s2 // a new string with content "Hello, world!" is created
Under the hood, memory is allocated for a new string of length len(s1)+len(s2), then bytes from s1 and s2 are copied into the new buffer. The original strings remain unchanged. This is important to consider when concatenating strings frequently to avoid unnecessary allocations — for this, strings.Builder is used.