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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.