Build strings efficiently
Build strings efficiently
For a few pieces, + is often the clearest option. For a known slice of strings, use strings.Join. When assembling many pieces incrementally, strings.Builder accumulates bytes and produces a string with String(). Its zero value is usable; actual performance depends on workload.
package main
import ( "fmt" "strings")
func main() { var b strings.Builder for _, s := range []string{"Go", " ", "Unicode"} { b.WriteString(s) } fmt.Println(b.String(), b.Len())}WriteString appends a string, returning a byte count and nil error for Builder. Here the results are intentionally ignored. Len counts bytes, not runes. Do not copy a non-zero Builder or use it concurrently without synchronization.
Expected output:
Go Unicode 10Reserve capacity and append runes
package main
import ( "fmt" "strings")
func main() { var b strings.Builder b.Grow(8) b.WriteRune('س') b.WriteString("Go") fmt.Println(b.String(), b.Len(), b.Cap() >= 8)}Grow reserves space for at least the requested additional byte count without changing length. WriteRune encodes a rune in UTF-8. Exact capacity and performance depend on implementation; do not assume a growth factor or claim a speedup without measurements.
Expected output:
سGo 4 trueTry it locally
Use Builder to append "Go", a colon, and "سلام". Print the result and byte length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strings and Unicode 08: Build strings efficiently
Check the lesson objective before moving on.
What does Builder.Len return?
What must you avoid with a non-zero Builder?