Senior
How can strings be efficiently concatenated in Go? What options are available?
sobes.tech AI
Answer from AI
In Go, there are several options for efficient string concatenation:
- strings.Builder — the optimal way for sequentially adding strings, minimizes allocations.
var builder strings.Builder
builder.WriteString("Hello")
builder.WriteString(", ")
builder.WriteString("World!")
result := builder.String()
-
bytes.Buffer — similar to strings.Builder, but works with bytes, also efficient.
-
strings.Join — convenient if you have a slice of strings to combine with a separator.
parts := []string{"Hello", "World", "from", "Go"}
result := strings.Join(parts, " ")
- Concatenation using the
+operator — suitable for a small number of strings, but inefficient for many concatenations due to creating new strings.
For large data volumes and loops, it's better to use strings.Builder or bytes.Buffer.