Sobes.tech
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:

  1. Operator + — simple and convenient for a small number of strings.
  2. strings.Builder — an efficient method for multiple concatenations, especially in loops.
  3. bytes.Buffer — similar to strings.Builder, but works with bytes.
  4. 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.Builder uses 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.