Strings Builder Assembles Text Incrementally

Assemble text with strings.Builder: appends write into one internal buffer, Grow preallocates capacity, and Reset empties content while keeping the buffer.

GoCli Tooling

Code

gosnippet
33 lines
package main

import (
	"fmt"
	"strings"
)

func render(rows []string) string {
	// Builder appends into one internal buffer, avoiding a full copy per + concatenation
	var b strings.Builder
	b.Grow(64) // preallocate capacity to reduce regrowth
	for i, row := range rows {
		if i > 0 {
			b.WriteString(", ")
		}
		b.WriteString(row)
	}
	return b.String()
}

func main() {
	fmt.Println(render([]string{"alpha", "beta", "gamma"}))

	// Length and capacity are separate: after writing four words the length no longer equals the capacity
	var a strings.Builder
	a.WriteString("keep")
	fmt.Println("len:", a.Len(), "cap:", a.Cap())

	// Reset empties the content but keeps the underlying capacity, so the buffer is reusable
	a.Reset()
	a.WriteString("again")
	fmt.Println(a.String())
}

How it works

Strings Builder Assembles Text Incrementally reduces to the functions render and main.

A single loop drives the file — for i, row := range rows.

Caveats

  • Self-contained — no imports beyond what the runtime already provides.

Using it

Signature: func render(rows []string) string

Running the file prints labeled results such as len: — each operation’s effect is visible in the output.

Running the file executes main, which drives render in order.

Key statements

func render(rows []string) string {
// Builder appends into one internal buffer, avoiding a full copy per + concatenation
var b strings.Builder
b.Grow(64) // preallocate capacity to reduce regrowth
for i, row := range rows {
if i > 0 {
b.WriteString(", ")
}
b.WriteString(row)
}
return b.String()
}

Interactive Tools for This Topic

FAQ

What does Strings Builder Assembles Text Incrementally print when run?
Run it as a complete program — the output lines carry labels such as `len:`.