How to Use strings.Builder in Go for Efficient String Concatenation
Use
strings.Builder in Go to efficiently build strings by creating a Builder, appending strings with WriteString, and getting the final string with String(). It avoids creating many intermediate strings and improves performance.Syntax
The strings.Builder type provides a way to build strings efficiently by appending parts without creating many temporary strings.
Key methods:
var b strings.Builder: declares a new Builder.b.WriteString(s string) (int, error): appends stringsto the Builder.b.String() string: returns the complete built string.
go
var b strings.Builder b.WriteString("Hello") b.WriteString(", ") b.WriteString("World!") result := b.String()
Example
This example shows how to use strings.Builder to join multiple strings efficiently and print the result.
go
package main import ( "fmt" "strings" ) func main() { var b strings.Builder b.WriteString("Go") b.WriteString(" ") b.WriteString("is") b.WriteString(" ") b.WriteString("fun!") finalString := b.String() fmt.Println(finalString) }
Output
Go is fun!
Common Pitfalls
Common mistakes when using strings.Builder include:
- Reusing the same Builder without resetting it, which appends to old data.
- Calling
String()before finishing all writes. - Ignoring the error returned by
WriteString(usually safe to ignore for strings).
To reset a Builder, use b.Reset() before starting new writes.
go
package main import ( "fmt" "strings" ) func main() { var b strings.Builder b.WriteString("Hello") fmt.Println(b.String()) // Prints: Hello // Without reset, appending continues b.WriteString(" World") fmt.Println(b.String()) // Prints: Hello World // Reset to clear previous content b.Reset() b.WriteString("New String") fmt.Println(b.String()) // Prints: New String }
Output
Hello
Hello World
New String
Quick Reference
| Method | Description |
|---|---|
| WriteString(s string) | Appends string s to the Builder |
| String() | Returns the built string so far |
| Reset() | Clears the Builder to reuse it |
| Grow(n int) | Pre-allocates space to improve performance |
Key Takeaways
Use strings.Builder to efficiently build strings without many temporary copies.
Always call String() after all writes to get the final string.
Reset the Builder with Reset() before reusing it to avoid appending to old data.
WriteString returns an error but it is usually safe to ignore for string writes.
Use Grow() to pre-allocate memory if you know the final size to improve speed.