UTF-8, ranging over strings, and the strings package.
The strings Package
The strings package contains the everyday text helpers. Here are the ones you'll
use again and again.
strings.Builder — efficient concatenation
Building a string with + in a loop is slow because each concatenation copies.
Use strings.Builder for serious string-building:
strings.Builder implements io.Writer, so anything that writes to an io.Writer
(fmt.Fprintf, json.NewEncoder, …) can target it.
Quick cheat-sheet
| You want… | Use |
| --------------------- | ------------------------------------------------ |
| count occurrences | strings.Count |
| pad / repeat | strings.Repeat |
| change case | strings.ToLower / ToUpper / Title (deprecated; use cases from golang.org/x/text) |
| trim | strings.TrimSpace, TrimLeft, TrimPrefix |
| find | strings.Index, LastIndex, IndexAny |
| compare case-insens. | strings.EqualFold |
| split by func | strings.FieldsFunc |
| split once at a sep | strings.Cut (Go 1.18+) |
strings.Cut — split once, cleanly
Cut is the modern alternative to Split when you only want to split on the
first occurrence:
key, value, ok := strings.Cut("foo=bar=baz", "=")
// key="foo", value="bar=baz", ok=true
The ok tells you whether the separator was found. Much nicer than indexing
into the result of Split.