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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

type Builder struct{ ... }   func (b *Builder) WriteString(s string) (int, error)

Parameters

ParameterDescription
WriteString / WriteByte / WriteRune Append text.
String() The result.
Grow(n) Reserve capacity.

Examples

Example 1
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.

Title-casing words
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.

Was this page helpful?