Senior
What are the ways to concatenate strings in Go? What is the difference between + and strings.Builder?
sobes.tech AI
Answer from AI
In Go, there are several ways to concatenate strings:
- Operator
+— simple and convenient for a small number of strings. strings.Builder— an efficient method for multiple concatenations, especially in loops.bytes.Buffer— similar tostrings.Builder, but works with bytes.fmt.Sprintf— string formatting, but less efficient for simple concatenation.
Difference between + and strings.Builder:
+creates a new string each time, which involves memory allocation and data copying. For a small number of operations, this is not critical.strings.Builderuses an internal buffer that expands as needed, minimizing memory allocations and copies. This is significantly more efficient for a large number of concatenations.
Example:
var sb strings.Builder
for _, s := range parts {
sb.WriteString(s)
}
result := sb.String()
Use + for simple cases and strings.Builder for complex or large concatenations.