Middle
How does string concatenation work in Go?.
sobes.tech AI
Answer from AI
In Go, strings are immutable sequences of bytes. Concatenation of strings is done using the + operator. This creates a new string into which data from both original strings is copied.
Example:
s1 := "Hello, "
s2 := "world!"
s3 := s1 + s2 // "Hello, world!"
If you need to concatenate many strings in a loop, it is better to use strings.Builder — it is more efficient as it minimizes memory allocations:
var b strings.Builder
for _, str := range sliceOfStrings {
b.WriteString(str)
}
result := b.String()