strings.Builder
- Version
- 1.27
- Since
- 1.10
- Review
- Draft
Summary#
A strings.Builder accumulates text while minimizing memory copying. Its zero value is ready to use. Grow(n) reserves room for at least n more bytes.
Syntax#
var builder strings.Builder
builder.Grow(size)
builder.WriteString(part)
result := builder.String()
builder.Reset()
Example#
package main
import (
"fmt"
"strings"
)
func main() {
var builder strings.Builder
builder.Grow(32)
for i, word := range []string{"build", "one", "string"} {
if i > 0 {
builder.WriteByte(' ')
}
builder.WriteString(word)
}
fmt.Fprintf(&builder, " (%d words)", 3)
result := builder.String()
fmt.Println(result)
fmt.Println(builder.Len())
builder.Reset()
fmt.Println(builder.Len(), len(result))
}
Expected output#
build one string (3 words)
26
0 26
Common mistakes#
Keep a builder in one variable once you call Grow or write to it. Pass a *strings.Builder to helpers such as fmt.Fprintf. Writing through a copy can panic.
Version applicability#
strings.Builder and all the methods used here require Go 1.10. Earlier versions commonly use bytes.Buffer to accumulate text.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0