Go 1.27 reference · Formatting, Strings and Text
Go strings.Builder Type
Build a string efficiently piece by piece without creating a new string for every concatenation.
Go 1.27
Syntax
type Builder struct{ ... } func (b *Builder) WriteString(s string) (int, error)
Parameters
| Parameter | Description |
|---|---|
WriteString / WriteByte / WriteRune |
Append text. |
String() |
The result. |
Grow(n) |
Reserve capacity. |
Examples
package main
import (
"fmt"
"strings"
)
func main() {
var b strings.Builder
for i := 1; i <= 3; i++ {
fmt.Fprintf(&b, "line %d\n", i)
}
b.WriteString("done")
fmt.Println(b.String())
}
Output
line 1 line 2 line 3 done
Run this on your computer — see “Get Started” for setup.
package main
import (
"fmt"
"strings"
)
func main() {
words := []string{"go", "is", "fun"}
var b strings.Builder
b.Grow(32)
for i, w := range words {
if i > 0 {
b.WriteByte(' ')
}
b.WriteString(strings.ToUpper(w[:1]) + w[1:])
}
fmt.Println(b.String(), b.Len())
}
Output
Go Is Fun 9
Run this on your computer — see “Get Started” for setup.
Related
strings.Split and strings.Join· Split a string into a slice around a separator, and join a slice of strings with a separator.fmt.Printf· Print formatted output using verbs like %v, %+v, %d, %s, %q, %.2f and %T, with width and alignment options.- Go Strings · tutorial