liveBook · Manning

Strings.Builder

As explained in 100 Go Mistakes and How to Avoid Them

strings.Builder is a Go type for efficiently accumulating string data and producing a final string.

Repeatedly concatenating strings with += can become expensive: because strings are immutable, each iteration reallocates a result and copies existing content. strings.Builder accumulates bytes internally, reducing repeated memory copying. section 5.4

Replace repeated += concatenation

Use the zero value, append each value with WriteString, and obtain the result with String: func concat(values []string) string { var sb strings.Builder for _, value := range values { _, _ = sb.WriteString(value) } return sb.String() } WriteString returns an error only to satisfy io.StringWriter; this implementation does not produce a non-nil error. Builder also accepts bytes through Write, one byte through WriteByte, and one rune through WriteRune. section 5.4

Choose the implementation according to input size, known capacity, and execution context:

  • Call Grow when the total byte length is known. Sum len(value) first, call sb.Grow(total), then write the values to reduce further allocation. section 5.4
  • Do not share a Builder between concurrent operations; its internal byte slice is appended to, so unsynchronized calls can race. section 5.4

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains immutability, internal byte-slice appends, interface-driven errors, Grow, and concurrency limits, then stops short of implementation source details.
Examples
Compares += concatenation with Builder, adds Grow based on summed byte lengths, and reports benchmark results for all three versions.
What it assumes
Assumes familiarity with Go strings, slices, methods, interfaces, and basic concurrency concerns.
What you can do after
Build it from scratch using WriteString, Grow, and String while avoiding unnecessary allocation and unsynchronized sharing.
How it connects
Connects strings.Builder to string immutability, io.StringWriter, byte slices, and concurrency safety.

Also explained in

Compare how 3 books explain strings.Builder →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.