strings.Builder
type in Go’s standard library provides several methods to help build and manipulate strings efficiently. The following are the primary methods available:
package main
import (
"fmt"
"strings"
)
func main() {
// Create a new strings.Builder
var builder strings.Builder
// Method 1: Write (using []byte)
builder.Write([]byte("Hello, "))
fmt.Println("After Write: ", builder.String()) // Output: Hello,
// Method 2: WriteByte
builder.WriteByte('w')
fmt.Println("After WriteByte: ", builder.String()) // Output: Hello, w
// Method 3: WriteRune
builder.WriteRune('o')
fmt.Println("After WriteRune: ", builder.String()) // Output: Hello, wo
// Method 4: WriteString
builder.WriteString("rld!")
fmt.Println("After WriteString: ", builder.String()) // Output: Hello, world!
// Method 5: String
result := builder.String()
fmt.Println("String Method: ", result) // Output: Hello, world!
// Method 6: Len
length := builder.Len()
fmt.Printf("Len Method: Length = %d\n", length) // Output: Len Method: Length = 13
// Method 7: Cap
capacity := builder.Cap()
fmt.Printf("Cap Method: Capacity = %d\n", capacity)
// Method 8: Reset
builder.Reset()
fmt.Println("After Reset: ", builder.String()) // Output: (empty string)
// Method 9: Grow
builder.Grow(50) // Preallocate space for 50 bytes
builder.WriteString("This is a new string.")
fmt.Println("After Grow and Write: ", builder.String()) // Output: This is a new string.
}