Strings, Runes, fmt Verbs, text/template & regexp
"In Go, a string is in effect a read-only slice of bytes." — Rob Pike, Strings, bytes, runes and characters in Go (The Go Blog)
Summary: A Go string is an immutable sequence of bytes that is usually UTF-8; len counts bytes, range decodes runes, and everything else (formatting, templates, regular expressions, Unicode normalization) is a library that works on those bytes with rules you must know to avoid silent bugs. Focus: bytes versus runes versus visible characters, invalid UTF-8 and utf8.RuneError, the strings package and strings.Builder, strconv and *NumError, every fmt verb and flag, Stringer/GoStringer/Formatter, %w, text/template (actions, pipelines, FuncMap, define/block, trimming, missingkey), regexp (RE2, no backtracking, precompiling), normalization and case folding with golang.org/x/text, Persian and Arabic text (ZWNJ, look-alike letters, digits, bidi), and zero-copy conversions. Learning goal: Predict what len, indexing and range return for any string, pick the cheapest correct way to build and parse text, read any fmt error string, write a safe template and a precompiled regular expression, and normalize Persian input so that search and comparison work.
This page is the complete reference for text handling in the Go standard library plus the one module outside it that every international service needs, golang.org/x/text. It owns the language and library mechanics. HTML pages with escaping, layouts and flash messages belong to html/template: Layouts, Caching, Forms, Flash Messages; the JSON and XML encoders and Base64 belong to JSON, XML, Struct Tags, Encoder/Decoder, Base64; time.Time formatting and number parsing from clocks belong to time.Time, Formatting/Parsing, Time Zones, Timers, math/rand & Number Parsing; the io.Reader and bufio.Scanner plumbing is in The io Package and Files, Directories, Paths, Temp Files, bufio & embed; interfaces such as fmt.Stringer are explained in Interfaces, Type Assertions, Type Switches & any; wrapping errors with %w is taught in Errors, Wrapping, Panic, Recover & Defer; slices as headers ([]byte, []rune) are in Arrays, Slices & Maps; full-text search engines are in Full-Text Search: PostgreSQL FTS vs Elasticsearch. Here you get the one model that ties text together.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why a string is bytes and not characters | Why it exists |
Spec, Go blog, fmt and regexp package docs | Where it comes from |
len, indexing, range, []rune, rune is int32 | The string model and Runes |
utf8.RuneError, \xff, utf8.ValidString | Invalid UTF-8 |
Cut, Fields, Split, Trim*, EqualFold, Map, SplitSeq | The strings package |
strings.Builder versus + versus bytes.Buffer | Building strings |
Atoi, ParseFloat, Quote, AppendInt, *NumError | strconv |
%v %+v %#v %T %q %x %p %08.3f %[1]d %*d | fmt verbs |
String(), GoString(), Format() | Stringer, GoStringer, Formatter |
%w, %!d(string=hi), go vet printf checks | Errorf, %w and vet |
Template actions: dot fields, pipelines, range, if, with | text/template basics |
FuncMap, template.Must, define, block, whitespace trimming, missingkey | Template functions, composition and errors |
| Escaping HTML | html/template |
RE2 syntax, named groups, FindAllStringSubmatch | regexp |
MustCompile at package level, regexp versus strings | Regexp performance |
NFC/NFD, cases.Fold, Turkish i | Normalization and case folding |
ZWNJ, Arabic Yeh, Persian digits, bidi, x/text/language | Persian and Arabic text |
string(b) allocations, unsafe.String | Conversions and allocations |
| Exact error and vet messages | Mechanics |
Real numbers from go test -bench | Measured costs |
mb_*, sprintf, preg_* and PCRE | For PHP/Laravel developers |
| Reproduce the outputs | Lab |
Everything in one minute
The three views of one string.
| View | Type | How you get it | Count of "é世" | Notes |
|---|---|---|---|---|
| Bytes | byte (uint8) | s[i], len(s) | 5 | Indexing never decodes |
| Code points (runes) | rune (int32) | for i, r := range s, []rune(s), utf8.RuneCountInString | 2 | i is a byte offset |
| Visible characters (graphemes) | none in the standard library | golang.org/x/text, rivo/uniseg | 2 | e plus U+0301 is 2 runes, 1 character |
The formatting verbs you use every day.
| Verb | Prints | Example | Output |
|---|---|---|---|
%v | Default format | Printf("%v", p) | {1 2 a} |
%+v | Struct with field names | Printf("%+v", p) | {X:1 Y:2 Tag:a} |
%#v | Go-syntax representation | Printf("%#v", p) | verbs.Point{X:1, Y:2, Tag:"a"} |
%T | Dynamic type | Printf("%T", p) | verbs.Point |
%q | Quoted string or rune | Printf("%q", "go") | "go" |
%x | Hex of bytes or integer | Printf("%x", "go") | 676f |
%08.3f | Zero-padded width 8, 3 decimals | Printf("%08.3f", 3.14159) | 0003.142 |
%[2]s %[1]s | Explicit argument index | Printf("%[2]s %[1]s", "a", "b") | b a |
%*d | Width taken from an argument | Printf("%*d", 5, 3) | 3 |
%p | Pointer address | Printf("%p", &x) | 0xc000012345 (varies) |
%w | Wrap an error (only in fmt.Errorf) | Errorf("x: %w", err) | x: ... plus Unwrap |
The tools and when to reach for them.
| Task | Reach for | Not for |
|---|---|---|
| Split on one separator, once | strings.Cut | Split then index [0] |
| Split on white space | strings.Fields | Split(s, " ") |
| Build in a loop | strings.Builder (with Grow) | s += x in a loop |
| String to number | strconv.Atoi, ParseFloat | fmt.Sscanf in hot paths |
| Number to string | strconv.Itoa, AppendInt | fmt.Sprint(n) in hot paths |
| Simple prefix, suffix, contains | strings.HasPrefix, Contains | a regexp |
| Pattern with groups | regexp compiled at package level | compiling inside a handler |
| Text with logic and loops | text/template | string concatenation |
| HTML output | html/template | text/template |
| Compare user-typed Unicode | norm.NFC plus cases.Fold | == or strings.ToLower alone |
Why it exists
Text is the interface between your program and everything else: files, the network, logs, databases, users. Languages have to pick what a "string" is. Go picked the smallest honest answer: a string is a read-only slice of bytes, because bytes are what files and sockets really carry. Everything above (code points, characters, languages) is built by libraries on top.
| Weaker, simpler | Stronger, richer |
|---|---|
| Byte strings: fast, no hidden decoding, any file fits | Unicode-aware strings: correct per character, but hidden costs and surprises |
strings and bytes: small, predictable | golang.org/x/text: normalization, case mapping, language matching |
regexp with a linear-time guarantee: no catastrophic backtracking | Perl-style engines: lookaround and backreferences, but a regex can hang a server |
fmt verbs: terse and reflective | text/template: logic, loops and functions in a separate file |
An everyday picture. A string is a strip of paper tape punched with bytes. len measures the tape in centimetres. A rune is a word written across one to four centimetres of tape. A visible character is what a reader perceives as one letter, which may be a base letter plus an accent mark glued on top. The tape cannot be edited: to change it you cut a new tape.
Three common misunderstandings, up front
- "
len(s)is the number of characters." It is the number of bytes.len("é")is 2 andlen("سلام")is 8. Useutf8.RuneCountInStringfor code points, and a grapheme library for what a user sees. - "
s[i]is the i-th character." It is the i-th byte. Slicings[:3]can cut a two-byte letter in half and produce invalid UTF-8. - "Go regexp supports everything PHP's
preg_*does." It supports RE2 syntax only: no lookahead, lookbehind or backreferences. In exchange the match time is linear in the input.
Where it comes from
The authoritative texts are the Go specification (string types, conversions between strings and byte or rune slices, for statements with a range clause), the Go blog post Strings, bytes, runes and characters in Go (Rob Pike, the clearest statement of the model), and Text normalization in Go (why norm exists and what NFC/NFD mean). The fmt rules are in the package documentation, read here from the Go 1.25.0 source of fmt/doc.go because pkg.go.dev returns HTTP 403 to automated fetchers; the same holds for text/template, regexp and regexp/syntax.
Three decisions explain most of the design. First, the spec says the range loop over a string decodes UTF-8 and, "If the iteration encounters an invalid UTF-8 sequence, the second value will be 0xFFFD, the Unicode replacement character, and the next iteration will advance a single byte in the string." Second, the regexp package documentation promises that the implementation "is guaranteed to run in time linear in the size of the input", following RE2 (a design Russ Cox describes in his article on regular expression matching); a Google RE2 syntax reference lists what is deliberately left out. Third, the language kept the string type tiny and moved Unicode algorithms into a separately versioned module, golang.org/x/text (source), so the standard library does not grow with every Unicode release. Go 1.24 added iterator forms of the splitting functions (strings.Lines, SplitSeq, FieldsSeq), see the Go 1.24 release notes.
The concept catalogue
The string model: immutable bytes Must-know
In plain words: a string value is two machine words, a pointer to some bytes and a length. You can read it, slice it, compare it and pass it around cheaply, but you can never change a byte inside it.
Common misunderstanding: "A Go string is a list of characters, and s[0] gives me the first letter." It is a list of bytes. The language does not require the bytes to be valid UTF-8; source code literals are UTF-8, but a string can hold any binary data, including a JPEG.
Definition: the spec defines a string type as the set of all strings of bytes, possibly empty, immutable once created, with length available through the built-in len (a constant for constant strings). s[i] yields a byte, is not addressable, and panics out of range. Slicing s[a:b] yields a new string header sharing the same bytes (no copy). Strings are compared bytewise with == and <.
1 s := "a" + "é" + "世" // bytes: 61 | C3 A9 | E4 B8 96
2 len(s) // 6
3 s[1] // 0xC3 (a byte, NOT the letter)
4 s[1:3] // "é" (slicing on rune boundaries is fine)
5 s[1:2] // "\xc3" invalid UTF-8, no panic, no error
6 s[0] = 'b' // compile error: cannot assign to s[0] (neither addressable nor a map index expression)Real scenario: a log line truncated with line[:80] that splits a Persian letter and makes the JSON log encoder emit U+FFFD; a hash of a file read into a string (works, strings hold bytes); a cache key built from user text that differs only in Unicode form.
| Operation | Cost | Notes |
|---|---|---|
len(s) | O(1) | Bytes |
s[i] | O(1) | A byte, bounds-checked |
s[a:b] | O(1) | Shares memory; a small substring keeps a large string alive |
s + t | O(n) | Allocates a new string |
[]byte(s), string(b) | O(n) | Copies (the compiler elides some copies) |
s == t | O(n) worst | Length check first |
Fix / how to use it: treat a string as bytes unless you decode. The snippet below measures one string at the three levels and shows the failure you get when you slice in the middle of a rune.
// Package runes shows the difference between bytes, runes and what a user
// calls a character.
package runes
import (
"unicode/utf8"
)
// Report describes one string at the three levels Go cares about.
type Report struct {
Bytes int
Runes int
Valid bool
}
// Inspect measures s. len(s) counts bytes, RuneCountInString counts decoded
// runes (an invalid byte counts as one RuneError rune), ValidString checks
// that the whole string is well-formed UTF-8.
func Inspect(s string) Report {
return Report{Bytes: len(s), Runes: utf8.RuneCountInString(s), Valid: utf8.ValidString(s)}
}
// Decoded is one step of a range loop over a string.
type Decoded struct {
Offset int
Rune rune
Width int
}
// Walk returns what `for i, r := range s` sees: the byte offset of each rune,
// the rune itself and how many bytes it took. Invalid bytes show up as
// utf8.RuneError with width 1.
func Walk(s string) []Decoded {
var out []Decoded
for i, r := range s {
w := utf8.RuneLen(r)
if r == utf8.RuneError {
// RuneLen reports 3 for U+FFFD, but the source consumed 1 byte
// when the input was invalid; decode again to learn the truth.
_, w = utf8.DecodeRuneInString(s[i:])
}
out = append(out, Decoded{Offset: i, Rune: r, Width: w})
}
return out
}
// Reverse reverses by rune. It is correct for code points, but it still
// separates a base letter from a combining mark that follows it.
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
// TruncateRunes cuts s to at most n runes without splitting a code point.
// Slicing s[:n] would cut bytes and can leave half of a UTF-8 sequence.
func TruncateRunes(s string, n int) string {
if n <= 0 {
return ""
}
count := 0
for i := range s {
if count == n {
return s[:i]
}
count++
}
return s
}
// FirstRune returns the first rune and its width, or (RuneError, 0) for "".
func FirstRune(s string) (rune, int) {
return utf8.DecodeRuneInString(s)
}$ go test ./runes
ok academy/strings-runes-formatting-templates/runesRunes, len, indexing and range Must-know
In plain words: a rune is one Unicode code point. for i, r := range s walks the string rune by rune; i is where that rune starts in bytes, r is the decoded value.
Common misunderstanding: "range over a string gives the same as for i := 0; i < len(s); i++." The index form gives bytes; the range form gives runes and jumps i by the byte width of each rune.
Definition: rune is an alias for int32 (a code point, 'x' literals are untyped rune constants). utf8.RuneCountInString(s) counts decoded runes, []rune(s) converts to a slice of code points (one allocation, 4 bytes per rune), string(r) for a rune builds a one-rune string (and string(65) from an integer is a vet warning), utf8.RuneLen(r) is the encoded width, utf8.DecodeRuneInString decodes one rune at the start, utf8.AppendRune appends the encoding to a byte slice.
1 s := "h" + "é" + "世" // 1 + 2 + 3 bytes = 6, 3 runes
2 for i, r := range s { ... }
3 i=0 r='h' U+0068 width 1
4 i=1 r='é' U+00E9 width 2
5 i=3 r='世' U+4E16 width 3 // i jumped by 2, then by 3
6 len(s)=6 utf8.RuneCountInString(s)=3 len([]rune(s))=3Real scenario: a username limit of 20 characters counted with len rejects a 10-letter Persian name; an input masking function that replaces the middle with * by byte index corrupts non-ASCII; a progress bar that pads a table with %-10s miscounts because fmt pads by rune count, not by display width.
| Task | Correct tool | Common mistake |
|---|---|---|
| Count code points | utf8.RuneCountInString(s) | len(s) |
| Take the first n runes | loop with range and slice at the byte offset | s[:n] |
| Reverse (code points) | []rune, swap, string | byte swap |
| Index the n-th rune | []rune(s)[n] (copy) or a counting loop | s[n] |
| Check ASCII only | loop over bytes, b < 0x80 | len(s) == RuneCount is also valid |
| Display width | a width library (East Asian wide, emoji) | rune count |
Fix / how to use it: the runes package above has Walk (what range sees), TruncateRunes (cut at a rune boundary) and Reverse (and its test shows that reversing a decomposed e plus U+0301 puts the accent first, which is why reversal by rune is still not reversal by character).
Invalid UTF-8 and utf8.RuneError Important
In plain words: when bytes are not valid UTF-8, Go does not fail. It decodes the bad byte as the replacement rune U+FFFD (written utf8.RuneError) and moves on one byte.
Common misunderstanding: "Strings in Go are always valid UTF-8." Only literals in your source are. Anything read from a file, a request or a database column may not be.
Definition: utf8.DecodeRuneInString returns (RuneError, 1) for invalid input and (RuneError, 0) for the empty string. range follows the same rule. []rune(s) converts each invalid byte to U+FFFD, so the round trip string([]rune(s)) is lossy. A genuine U+FFFD in the text is three bytes (EF BF BD); to tell it from an error check the width. utf8.ValidString is the validator; strings.ToValidUTF8(s, "?") replaces runs of invalid bytes with a string you choose.
1 in := "a\xffb" // 0xFF can never appear in UTF-8
2 utf8.ValidString(in) // false
3 len(in) = 3
4 range in -> (0,'a') (1,U+FFFD width 1) (2,'b')
5 string([]rune(in)) = "a" + U+FFFD + "b" // 5 bytes: the input changed
6 json.Marshal(in) // encoder replaces the bad byte with U+FFFDReal scenario: a CSV exported from Excel in Windows-1256 (Arabic) and read as UTF-8 yields replacement characters; a PostgreSQL text column rejects the same bytes with invalid byte sequence for encoding "UTF8": 0xff; a gateway that truncates a request body mid-rune at a size limit.
| Source | What happens | Defence |
|---|---|---|
range s | Yields U+FFFD, advances 1 byte | Validate at the boundary |
[]rune(s) | Bad bytes become U+FFFD (lossy) | Keep the original string |
encoding/json Marshal | Replaces bad bytes with U+FFFD | Reject earlier if exact bytes matter |
PostgreSQL text (UTF8) | Error 22021 on insert | Validate or convert in the app |
regexp | . matches each bad byte as U+FFFD | Validate first |
Fix / how to use it: validate once where text enters (HTTP body, file, queue message) with utf8.ValidString and reject or repair with strings.ToValidUTF8; inside the program assume valid text.
The strings package Must-know
In plain words: the strings package is the standard toolbox: find, split, join, replace, trim, change case, compare. Most "I need a regexp" problems are solved here.
Common misunderstanding: "strings.Split(s, " ") splits on white space." It splits on exactly one space; consecutive spaces yield empty strings, and tabs and newlines are ignored. strings.Fields splits on any run of Unicode white space and never returns empty strings.
Definition: Cut(s, sep) returns before, after and a found flag (Go 1.18). Split, SplitN, SplitAfter, Fields, FieldsFunc split. Join, Repeat, Replace, ReplaceAll, NewReplacer build. Trim and TrimLeft/TrimRight remove any rune in a cutset; TrimPrefix/TrimSuffix remove one exact prefix or suffix. ToUpper/ToLower/Title-like mapping uses simple Unicode case mapping; EqualFold compares with simple case folding; Map applies a function to each rune (returning a negative value drops it). Contains, Index, HasPrefix, Count, LastIndex, IndexByte, IndexFunc search. Since Go 1.24 Lines, SplitSeq, SplitAfterSeq, FieldsSeq and FieldsFuncSeq return iterators that avoid allocating the whole slice.
1 strings.Split("a,b,,c", ",") -> ["a" "b" "" "c"]
2 strings.Split("", ",") -> [""] // one empty string, not zero
3 strings.Fields(" a b\tc\n") -> ["a" "b" "c"]
4 strings.Cut("k=v=w", "=") -> "k", "v=w", true
5 strings.Trim("xxhixx", "x") -> "hi" // cutset
6 strings.TrimPrefix("xxhixx", "xx") -> "hixx" // exact prefix once
7 strings.EqualFold(K-sign, "k") -> true // U+212A folds to kReal scenario: parsing Header: value lines (Cut on the first colon only, so values containing colons survive); splitting a PATH-like list; building a URL slug; normalising identifiers with EqualFold; ranging over a 2 GB log with strings.Lines (Go 1.24) instead of Split(log, "\n").
| Function | Use it for | Gotcha |
|---|---|---|
Cut | One separator, first occurrence | Replaces SplitN(s, sep, 2) and Index plus slicing |
Fields | Words separated by any white space | Splits on unicode.IsSpace, which includes the no-break space U+00A0 |
Split | Fixed separator | Split("", ",") returns one empty string |
Trim | Remove a set of runes at both ends | The second argument is a set, not a prefix |
TrimPrefix | Remove one exact prefix | No-op when absent |
EqualFold | Case-insensitive equality | Simple folding: ß is not SS; no normalization |
Replace / ReplaceAll | Literal replacement | Not a regexp |
Map | Per-rune transformation or filtering | Negative return drops the rune |
NewReplacer | Many replacements in one pass | One pass, not repeated: build once and reuse |
Fix / how to use it: the builder package below holds ParseKV, ParseHeader, Words, Slug, TrimDemo and SameIdentifier, each pinned by a test.
// Package builder compares the ways to assemble a string and shows the
// strings helpers that replace hand-written loops.
package builder
import (
"bytes"
"strings"
)
// ConcatPlus builds with += : every step allocates a new string and copies.
func ConcatPlus(parts []string) string {
s := ""
for _, p := range parts {
s += p
}
return s
}
// ConcatBuilder builds with strings.Builder and a pre-sized buffer.
func ConcatBuilder(parts []string) string {
n := 0
for _, p := range parts {
n += len(p)
}
var b strings.Builder
b.Grow(n)
for _, p := range parts {
b.WriteString(p)
}
return b.String()
}
// ConcatBuffer builds with bytes.Buffer; String() copies the bytes.
func ConcatBuffer(parts []string) string {
var b bytes.Buffer
for _, p := range parts {
b.WriteString(p)
}
return b.String()
}
// ConcatJoin is what you want when you already have the slice.
func ConcatJoin(parts []string) string { return strings.Join(parts, "") }
// KV is a parsed "key=value" pair.
type KV struct{ Key, Value string }
// ParseKV splits "key=value" with strings.Cut. ok is false without '='.
func ParseKV(s string) (KV, bool) {
k, v, ok := strings.Cut(s, "=")
if !ok {
return KV{}, false
}
return KV{Key: strings.TrimSpace(k), Value: strings.TrimSpace(v)}, true
}
// ParseHeader splits "Name: value" on the first colon only.
func ParseHeader(line string) (name, value string, ok bool) {
name, value, ok = strings.Cut(line, ":")
return strings.TrimSpace(name), strings.TrimSpace(value), ok
}
// Words splits on runs of white space. Split would return empty strings.
func Words(s string) []string { return strings.Fields(s) }
// Slug lower-cases, keeps letters and digits and joins words with '-'.
func Slug(s string) string {
mapped := strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
return r
case r >= 'A' && r <= 'Z':
return r + ('a' - 'A')
default:
return ' '
}
}, s)
return strings.Join(strings.Fields(mapped), "-")
}
// TrimDemo returns the results of the four trim families on one input so a
// test can pin their different meanings.
func TrimDemo() [4]string {
const s = "xxhixx"
return [4]string{
strings.Trim(s, "x"), // both ends, any of the cutset
strings.TrimPrefix(s, "xx"), // exact prefix, once
strings.TrimSuffix(s, "xx"), // exact suffix, once
strings.TrimLeft("xyxhi", "xy"), // cutset, left only
}
}
// SameIdentifier compares without case: EqualFold uses Unicode simple
// folding, which is not the same as strings.ToLower(a) == strings.ToLower(b).
func SameIdentifier(a, b string) bool { return strings.EqualFold(a, b) }Building strings: strings.Builder, + and bytes.Buffer Must-know
In plain words: adding strings with += in a loop copies everything on every step, so ten thousand pieces cost about fifty million byte copies. A strings.Builder appends into one growing buffer and hands you the result at the end with no extra copy.
Common misunderstanding: "The compiler optimises s += x in a loop." It optimises a single expression like a + b + c into one allocation, but not repeated assignment across loop iterations.
Definition: the documentation says: "A Builder is used to efficiently build a string using [Builder.Write] methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder." A copy of a used Builder panics on the next write with strings: illegal use of non-zero Builder copied by value. Grow(n) reserves capacity so appends do not reallocate. bytes.Buffer is a read-write byte buffer: its String() copies the bytes, it can also be read from, and it is the right tool when the destination needs io.Reader or you are building bytes. strings.Join is the best choice when the parts already sit in a slice.
1 parts = 256 words of about 6 bytes (1.5 KB result)
2 s += p -> 255 allocations, 165 KB allocated (each step copies the prefix)
3 Builder+Grow -> 1 allocation, 1.3 KB
4 bytes.Buffer -> 7 allocations (growth), String() copies
5 strings.Join -> 1 allocationReal scenario: rendering a CSV export row by row; generating SQL fragments (parameters, never values, see OWASP Top 10); assembling a log line; writing a response through io.Writer (use fmt.Fprintf(w, ...) directly instead of building a string first).
| Technique | Allocations for 256 parts | Best when |
|---|---|---|
s += p in a loop | 255 | Two or three pieces, not in a loop |
strings.Builder with Grow | 1 | You build in a loop and know the size |
strings.Builder without Grow | several (capacity doubles) | Size unknown |
bytes.Buffer | 7 and a copy on String() | You also need to read, or you build bytes |
strings.Join | 1 | Parts already in a slice |
fmt.Sprintf per piece | 1 or more per call | Not for hot paths |
Fix / how to use it: the builder snippet has all four variants with a test that pins the allocation counts (testing.AllocsPerRun) and a test that shows the copy panic. Real benchmark numbers are in Measured costs.
strconv: numbers, quotes and *NumError Must-know
In plain words: strconv converts between strings and numbers, booleans and quoted literals. Parsing returns an error you must check; formatting never fails.
Common misunderstanding: "Atoi trims spaces and accepts 1,000 or 1e3." It accepts an optional sign and decimal digits only. A leading space, a comma or an exponent is a syntax error. ParseFloat accepts 1e3, NaN and Inf, but not 1,5.
Definition: Itoa(n) is FormatInt(int64(n), 10). Atoi(s) is ParseInt(s, 10, 0) as an int. ParseInt(s, base, bitSize) and ParseUint accept base 0 (prefixes 0x, 0b, 0o, and underscores). ParseFloat(s, 64), ParseBool (accepts 1 t T TRUE true True 0 f F FALSE false False), Quote, QuoteToASCII, Unquote, and the allocation-free AppendInt, AppendFloat, AppendQuote. Failures are *strconv.NumError{Func, Num, Err} where Err is strconv.ErrSyntax or strconv.ErrRange (or an invalid-base/bit-size error); NumError implements Unwrap, so errors.Is(err, strconv.ErrRange) works.
1 strconv.Atoi("42") -> 42, nil
2 strconv.Atoi("12a") -> 0, strconv.Atoi: parsing "12a": invalid syntax
3 strconv.Atoi("99999999999999999999") -> max int, strconv.Atoi: parsing "99999999999999999999": value out of range
4 strconv.ParseFloat("1,5", 64) -> 0, strconv.ParseFloat: parsing "1,5": invalid syntax
5 strconv.ParseUint("70000", 10, 16) -> 65535, ...: value out of range // result is the clamped maximumReal scenario: parsing a PORT environment variable and rejecting 70000; a CSV importer that must say which row and column failed (wrap the NumError); a metrics exporter that formats a million lines per second (use AppendFloat into a reused buffer); a query-string ?page=0x10 accepted when base 0 is used by mistake.
| Task | Function | On bad input |
|---|---|---|
int from decimal text | Atoi | *NumError with ErrSyntax or ErrRange |
| Sized or unsigned, other bases | ParseInt/ParseUint(s, base, bits) | Value clamped on ErrRange |
| Float | ParseFloat(s, 64) | ErrRange for overflow, NaN and Inf accepted |
| Boolean | ParseBool | ErrSyntax |
| Go literal for logs | Quote, QuoteToASCII | Always valid |
| Append to a buffer | AppendInt, AppendFloat, AppendQuote | Zero allocations when capacity suffices |
| Money | integer cents, never float64 | See Values, Variables, Constants, iota Enums & Zero Values |
Fix / how to use it: ParsePort in the snippet wraps with %w and Classify branches with errors.Is and errors.As; the test shows that AppendRow does zero allocations when the buffer has capacity.
// Package conv wraps strconv with the error handling a service needs.
package conv
import (
"errors"
"fmt"
"strconv"
)
// ParsePort parses a TCP port from user input.
func ParsePort(s string) (uint16, error) {
n, err := strconv.ParseUint(s, 10, 16)
if err != nil {
return 0, fmt.Errorf("port %q: %w", s, err)
}
if n == 0 {
return 0, fmt.Errorf("port %q: must be 1..65535", s)
}
return uint16(n), nil
}
// Classify says what kind of strconv failure err is.
func Classify(err error) string {
var ne *strconv.NumError
switch {
case err == nil:
return "ok"
case errors.Is(err, strconv.ErrSyntax):
return "syntax"
case errors.Is(err, strconv.ErrRange):
return "range"
case errors.As(err, &ne):
return "other:" + ne.Err.Error()
default:
return "unknown"
}
}
// AppendRow appends "id,price" to dst without any intermediate string.
func AppendRow(dst []byte, id int64, price float64) []byte {
dst = strconv.AppendInt(dst, id, 10)
dst = append(dst, ',')
return strconv.AppendFloat(dst, price, 'f', 2, 64)
}
// Quoted returns the Go-syntax literal for s.
func Quoted(s string) string { return strconv.Quote(s) }
// QuotedASCII escapes every non-ASCII rune.
func QuotedASCII(s string) string { return strconv.QuoteToASCII(s) }fmt verbs, flags, width and argument indexes Must-know
In plain words: Printf-family functions take a format string with verbs such as %d and %s. The verb says how to print the next argument; flags and numbers in between say width, padding and precision.
Common misunderstanding: "%v is always safe." %v never fails, but it prints exactly what the type's String or Error method returns, which may be a secret or a huge value; and %d with a string prints %!d(string=hi) at run time, not a compile error (the compiler does not check; go vet does).
Definition: the format is %[argindex][flags][width][.precision]verb. Width and precision may be * (taken from an argument) or a number; [n] selects argument n explicitly and subsequent verbs continue after it. Flags: + sign (or field names for %+v), - pad right, # alternate form (0x for %#x, Go syntax for %#v), space, 0 pad with zeros. The family: Print/Println/Printf (stdout), Sprint* (returns a string), Fprint* (any io.Writer), Append* (appends to a byte slice), Errorf (an error).
1 fmt.Sprintf("%v|%+v|%#v|%T", p, p, p, p)
2 {1 2 a}|{X:1 Y:2 Tag:a}|verbs.Point{X:1, Y:2, Tag:"a"}|verbs.Point
3 fmt.Sprintf("%08.3f", 3.14159) -> "0003.142"
4 fmt.Sprintf("%-10s|%*d|", "apple", 5, 3) -> "apple | 3|"
5 fmt.Sprintf("%[2]s %[1]s %[2]s", "a", "b") -> "b a b"
6 fmt.Sprintf("%x % x %X", "go", "go", "go") -> "676f 67 6f 676F"
7 fmt.Sprintf("%U %c %q", 0x1F600, 'A', 'x') -> "U+1F600 A 'x'"Real scenario: log lines with %+v on a config struct; a CLI table with %-12s %8.2f; a debug print of a pointer with %p; hex-dumping a digest with %x; i18n templates that need %[2]s ... %[1]s because word order differs between languages.
| Verb | Applies to | Notes |
|---|---|---|
%v %+v %#v | Any | Default, with field names, Go syntax |
%T | Any | Dynamic type, e.g. *verbs.Point, []int, map[string]int |
%% | none | A literal percent sign |
%t | bool | true or false |
%d %b %o %x %X %c %q %U | Integers | Decimal, binary, octal, hex, character, quoted rune, U+1F600 |
%e %f %g | Floats | Scientific, fixed, shortest-form (%g of 1e21 is 1e+21) |
%s %q %x %X | Strings, byte slices | Plain, Go-quoted, hex of the bytes (space flag separates) |
%p | Pointers, slices, maps, channels, funcs | Address; varies between runs |
%w | Errors, only in fmt.Errorf | See Errorf |
Fix / how to use it: the verbs package pins every row above with exact expected strings, and Row shows %-10s, %*d and %08.3f together.
// Package verbs demonstrates fmt verbs and the Stringer, GoStringer and
// Formatter interfaces.
package verbs
import (
"errors"
"fmt"
"io"
)
// Point is a plain struct used to show %v, %+v, %#v and %T.
type Point struct {
X, Y int
Tag string
}
// Money implements fmt.Stringer: %v and %s print "12.50 EUR".
type Money struct {
Cents int64
Currency string
}
func (m Money) String() string {
return fmt.Sprintf("%d.%02d %s", m.Cents/100, m.Cents%100, m.Currency)
}
// Token hides its secret everywhere, including %#v, through GoStringer.
type Token struct{ Secret string }
func (Token) String() string { return "Token(****)" }
func (Token) GoString() string { return "verbs.Token{Secret:\"****\"}" }
// ID implements fmt.Formatter and so controls every verb itself.
type ID uint32
// Format prints %d as the number, %x as hex, %s as "id-N" and honours the
// '#' flag by adding a prefix.
func (id ID) Format(f fmt.State, verb rune) {
switch verb {
case 'd':
fmt.Fprintf(f, "%d", uint32(id))
case 'x':
if f.Flag('#') {
io.WriteString(f, "0x")
}
fmt.Fprintf(f, "%x", uint32(id))
case 's', 'v':
fmt.Fprintf(f, "id-%d", uint32(id))
default:
fmt.Fprintf(f, "%%!%c(verbs.ID=%d)", verb, uint32(id))
}
}
// Row formats a fixed-width table row: %-10s pads right, %*d takes the width
// from an argument and %08.3f zero-pads a float.
func Row(name string, qty, width int, price float64) string {
return fmt.Sprintf("%-10s|%*d|%08.3f", name, width, qty, price)
}
// Reorder uses explicit argument indexes: the same value twice, then another.
func Reorder(a, b string) string {
return fmt.Sprintf("%[2]s %[1]s %[2]s", a, b)
}
// Wrap shows %w: only fmt.Errorf understands it.
func Wrap(err error) error { return fmt.Errorf("load config: %w", err) }
// WrapMany wraps two errors; the result unwraps to both (Go 1.20+).
func WrapMany(a, b error) error { return fmt.Errorf("both failed: %w and %w", a, b) }
// NotWrapped uses %v: the text is kept but errors.Is can no longer see the
// original.
func NotWrapped(err error) error { return fmt.Errorf("load config: %v", err) }
// Describe returns one line per verb for a Point so the test can pin the
// exact output.
func Describe(p Point) []string {
return []string{
fmt.Sprintf("%v", p),
fmt.Sprintf("%+v", p),
fmt.Sprintf("%#v", p),
fmt.Sprintf("%T", p),
fmt.Sprintf("%v", &p) + "|" + fmt.Sprintf("%T", &p),
}
}
// Sentinel is used by tests to check errors.Is through Wrap.
var Sentinel = errors.New("sentinel")Stringer, GoStringer, Formatter Important
In plain words: if your type has a String() string method, fmt calls it for %v and %s. Two more interfaces let you control %#v (GoString) and everything (Format).
Common misunderstanding: "My String() method only changes how it prints, so it is harmless." It changes what appears in logs and errors, it is called with the type's value or pointer according to the method set (a pointer-receiver String is not used when you print a value), and a String that calls fmt.Sprintf("%v", t) on its own receiver recurses forever.
Definition: fmt.Stringer is String() string; fmt.GoStringer is GoString() string (used by %#v); fmt.Formatter is Format(f fmt.State, verb rune) where f is an io.Writer that also reports width, precision and flags. The dispatch order is shown in the diagram: Formatter first, then GoStringer for %#v, then error and Stringer for verbs valid on strings, then reflection. A panic in String is caught and printed as %!s(PANIC=bad); a nil receiver prints <nil>.
1 type Money struct{ Cents int64; Currency string }
2 func (m Money) String() string { ... "12.50 EUR" }
3 fmt.Sprintf("%v %s %d", m, m, m.Cents) -> "12.50 EUR 12.50 EUR 1250"
4 func (m Money) String() string { return fmt.Sprintf("%v", m) } // infinite recursion
5 go vet: fmt.Sprintf format %v with arg m causes recursive (pkg.Money).String method call
6 at run time: runtime: goroutine stack exceeds 1000000000-byte limit, then fatal error: stack overflowReal scenario: a Token or Password type whose String and GoString print **** so a stray %+v in a log cannot leak it; a Money type that prints currency; an ID type with Format that prints hex under %x; an enum with String() generated by stringer.
| Interface | Method | Triggered by | Typical use |
|---|---|---|---|
fmt.Stringer | String() string | %v, %s, Println, %q, %x | Human-readable form |
error | Error() string | same, and takes priority over Stringer | Error messages |
fmt.GoStringer | GoString() string | %#v | Redaction, debug output |
fmt.Formatter | Format(State, rune) | every verb | Full control, big numbers, units |
Fix / how to use it: the Token type in the snippet hides its secret under %v, %s and %#v; ID.Format shows %d, %x, %#x, %s and an unknown verb. Value receivers make both value and pointer print correctly; see Structs, Methods, Constructors, Embedding & Struct Tags for method sets.
Errorf, %w, wrong arguments and go vet Important
In plain words: fmt.Errorf with %w builds an error that remembers the one it wraps, so callers can still test for it with errors.Is. Using %v instead keeps only the text. go vet reads your format strings and tells you about mistakes before they run.
Common misunderstanding: "%w works in Sprintf and Printf." It is valid only in fmt.Errorf (and it is invalid with a non-error argument). Anywhere else it prints %!w(...), and vet reports fmt.Sprintf does not support error-wrapping directive %w.
Definition: since Go 1.20 Errorf may contain more than one %w, and the result's Unwrap() []error returns all of them. Mistakes in a format string do not panic; they produce marked text: %!d(string=hi) (wrong type), %!(EXTRA string=guys) (too many arguments), %!d(MISSING) (too few), %!(BADWIDTH), %!(BADPREC), %!(BADINDEX), %!(NOVERB) (a trailing %). The printf analyzer in go vet (run automatically by go test) checks calls to Printf-like functions, including your own wrappers, and reports them at build time.
1 fmt.Errorf("load: %w", io.EOF) // errors.Is(err, io.EOF) = true
2 fmt.Errorf("load: %v", io.EOF) // errors.Is(err, io.EOF) = false
3 fmt.Errorf("a: %w and %w", e1, e2) // Is(e1), Is(e2) both true (Go 1.20+)
4 fmt.Sprintf("%w", err) // "%!w(*errors.errorString=&{sentinel})"
5 $ go vet ./...
6 main.go:6:14: fmt.Printf format %d has arg "hi" of wrong type string
7 main.go:7:2: fmt.Println call has possible Printf formatting directive %d
8 main.go:8:19: fmt.Sprintf does not support error-wrapping directive %wReal scenario: a repository returning fmt.Errorf("get user %d: %w", id, err) so the HTTP layer can map sql.ErrNoRows to 404; a deploy broken by a Printf missing an argument discovered in production because vet was not in CI; %w accidentally written as %v in a refactor so the retry middleware stopped recognising context.DeadlineExceeded.
| Mistake | Output at run time | go vet message |
|---|---|---|
Printf("%d", "hi") | %!d(string=hi) | format %d has arg "hi" of wrong type string |
Printf("hi", "guys") | hi%!(EXTRA string=guys) | call has arguments but no formatting directives |
Printf("hi%d") | hi%!d(MISSING) | format %d reads arg #1, but call has 0 args |
Printf("%*s", 4.5, "hi") | %!(BADWIDTH)hi | uses non-int 4.5 as argument of * |
Sprintf("100%") | 100%!(NOVERB) | Sprintf format % is missing verb at end of string |
Println("x %d", 3) | x %d 3 | call has possible Printf formatting directive %d |
Sprintf("%w", err) | %!w(...) | does not support error-wrapping directive %w |
Fix / how to use it: run go vet ./... (or go test) in CI; let golangci-lint enable govet and errorlint (which flags %v where %w was meant). The verbs tests build bad formats through a variable so vet does not reject the test file itself.
text/template: actions, pipelines, variables Must-know
In plain words: a template is text with holes. Anything between double braces is an action: print a field, loop over a list, test a condition. You parse the template once and execute it many times with different data.
Common misunderstanding: "text/template is safe for HTML." It does no escaping at all. For HTML, e-mail HTML parts or anything that reaches a browser use html/template.
Definition: data is passed as dot (.). .Name selects a field or a map key, .Method calls a method (with no arguments, or arguments after the name). A pipeline chains commands with |, the result of each is the last argument of the next (.Customer | upper | printf "%-10s"). Variables: $x := pipeline declares, $x = pipeline assigns, $ is the root data. Control actions: if/else if/else, range (over slice, array, map in sorted key order or channel, with an else branch for empty), with (changes dot, skipped when empty), template "name" pipeline (call another template), block, define, break, continue. Comments are /* ... */ inside an action. Built-in functions: and, or, not, len, index, slice, print, printf, println, html, js, urlquery, call, and comparisons eq, ne, lt, le, gt, ge. Truth: false, 0, nil pointer or interface, and empty array, slice, map or string are false.
1 Order #{{.ID}} for {{.Customer | upper}} -> Order #7 for ADA
2 {{range $i, $it := .Items}}{{$i}} {{$it.SKU}} -> loop with index and element
3 {{else}}(no items){{end}} -> runs when the range is empty
4 {{with .Note}}Note: {{.}}{{end}} -> skipped when Note is nil or ""
5 {{if gt (len .Items) 2}}bulk{{else if eq (len .Items) 0}}empty{{else}}regular{{end}}Real scenario: a plain-text e-mail body, a generated nginx.conf or Kubernetes manifest, a CLI report, a code generator.
| Action | Meaning | Note |
|---|---|---|
.Field, .Method, .Key | Select from dot | Fields must be exported |
$var := x | Declare a variable | Scope ends at the enclosing action's end |
if / else if / else | Conditional | Uses truthiness above |
range $i, $e := .L | Loop | Map keys sorted; else for empty |
with | Rebind dot when non-empty | Often used for optional fields |
template "x" . | Call a named template | Dot must be passed explicitly |
block "x" . | Define and call in one | Overridable default |
x | f | Pipeline | Result becomes the last argument of f |
printf, len, index, eq | Built-in functions | eq can compare against several values |
Fix / how to use it: the tmpl package renders a receipt with every construct above and the test pins the whole output.
// Package tmpl renders plain-text output (mail bodies, config files, CLI
// reports) with text/template. It does not escape anything: for HTML use
// html/template.
package tmpl
import (
"bytes"
"fmt"
"strings"
"text/template"
)
// Item is one order line.
type Item struct {
SKU string
Qty int
Cents int64
}
// Order is the data root passed as dot.
type Order struct {
ID int
Customer string
Items []Item
Note *string
Meta map[string]string
}
// Total is a method callable from a template as {{.Total}}.
func (o Order) Total() int64 {
var sum int64
for _, it := range o.Items {
sum += int64(it.Qty) * it.Cents
}
return sum
}
// Funcs is the FuncMap. It must be installed BEFORE Parse, because function
// names are resolved while parsing.
var Funcs = template.FuncMap{
"upper": strings.ToUpper,
"money": func(cents int64) string { return fmt.Sprintf("%d.%02d", cents/100, cents%100) },
"mustPositive": func(n int) (int, error) {
if n <= 0 {
return 0, fmt.Errorf("quantity must be positive, got %d", n)
}
return n, nil
},
}
// Receipt is parsed once at package level with Must: a syntax error is a
// programming error and should stop the program at start-up.
var Receipt = template.Must(template.New("receipt").Funcs(Funcs).Parse(receiptText))
const receiptText = `{{- define "line" -}}
{{.SKU | printf "%-6s"}} x{{.Qty}} {{money .Cents}}
{{- end -}}
Order #{{.ID}} for {{.Customer | upper}}
{{range $i, $it := .Items -}}
{{$i | printf "%02d"}} {{template "line" $it}}
{{else -}}
(no items)
{{end -}}
{{with .Note}}Note: {{.}}
{{end -}}
{{if gt (len .Items) 2}}bulk order
{{else if eq (len .Items) 0}}empty order
{{else}}regular order
{{end -}}
Total: {{.Total | money}}
`
// Render executes Receipt into a string.
func Render(o Order) (string, error) {
var buf bytes.Buffer
if err := Receipt.Execute(&buf, o); err != nil {
return "", err
}
return buf.String(), nil
}
// Page demonstrates block: a default body that a derived set can override.
const pageBase = `<{{block "title" .}}Default title{{end}}> {{block "body" .}}default body{{end}}`
// RenderPage renders pageBase, optionally overriding the blocks.
func RenderPage(override string, data any) (string, error) {
t, err := template.New("page").Parse(pageBase)
if err != nil {
return "", err
}
if override != "" {
if t, err = t.Parse(override); err != nil {
return "", err
}
}
var b strings.Builder
if err := t.Execute(&b, data); err != nil {
return "", err
}
return b.String(), nil
}
// RenderWithOption executes text with the given missingkey option on a map.
func RenderWithOption(text, option string, data map[string]any) (string, error) {
t, err := template.New("opt").Option("missingkey=" + option).Parse(text)
if err != nil {
return "", err
}
var b strings.Builder
err = t.Execute(&b, data)
return b.String(), err
}Template functions, composition, trimming and errors Important
In plain words: you can add your own functions to a template, define reusable pieces, strip stray blank lines, and decide what happens when a key is missing. Errors in the template text show up at parse time; errors in the data show up at execute time.
Common misunderstanding: "If the template parsed, it will run." Parsing checks syntax and that functions exist. Whether .Missing is a field of your data type is only known when you execute, so a typo in a field name fails in production at the first request that reaches it.
Definition: template.New(name).Funcs(funcMap).Parse(text): Funcs must be called before Parse because names are resolved while parsing (an unknown function is the parse error function "nosuch" not defined). A function returns one value, or a value and an error; a non-nil error aborts execution. template.Must(t, err) panics when err is non-nil, so use it for templates that are parsed at start-up. define "name" ... end declares a named template; template "name" . calls it; block "name" . ... end is a define plus an immediate call, so a later Parse can override it (the base layout pattern). Whitespace trimming: an opening delimiter followed by a space and a minus sign removes all white space before the action, and a minus sign, a space and a closing delimiter removes all white space after it (the timeline below shows both); the space next to the dash is required. Option("missingkey=...") controls map lookups for absent keys: default (or invalid) prints <no value>, zero returns the zero value of the element type, error stops with map has no entry for key "b". The documentation notes that Execute can write part of the output before it fails; render into a buffer if you need all-or-nothing. A *Template is safe for concurrent Execute calls once parsed.
1 template.New("bad").Parse("{{.Name") -> template: bad:1: unclosed action
2 template.New("fn").Parse("{{nosuch .}}") -> template: fn:1: function "nosuch" not defined
3 t.Execute(w, struct{ Name string }{"a"}) with "{{.Missing}}"
4 -> template: x:1:2: executing "x" at <.Missing>: can't evaluate field Missing in type struct { Name string }
5 "start {{mustPositive .}} end" with 0 -> w received "start " then: quantity must be positive, got 0
6 "a {{- "x" -}} b" -> "axb"Real scenario: a mailer service with a layout template and per-message block overrides; a Helm-like config generator where a missing value must fail the build (missingkey=error); a template with a money function formatting cents; a test that parses every template in the repository at start-up with Must so a typo breaks CI, not a customer.
| Need | Mechanism | Detail |
|---|---|---|
| Custom function | Funcs(template.FuncMap{...}) before Parse | Returns 1 value or (value, error) |
| Panic on a bad template at start-up | template.Must(template.New(..).Parse(..)) | Package-level var |
| Reusable fragment | define and template "name" dot | Dot is not inherited |
| Overridable default | block | Later Parse of define replaces it |
| Remove blank lines | Trim markers: minus sign inside the delimiters | Space required next to the dash |
| Absent map key | Option("missingkey=error") | default prints <no value> |
| Whole-or-nothing output | Execute into bytes.Buffer, then copy | Partial output otherwise |
| Concurrency | One parsed *Template, many Execute | Do not Parse while executing |
| Files | template.ParseFiles, ParseGlob, ParseFS with embed | Name is the base file name |
Fix / how to use it: RenderPage in the snippet shows block with and without an override, RenderWithOption shows the three missingkey modes, and the tests cover the exact parse and execute error strings above.
html/template: the same API, with escaping Good to know
In plain words: html/template has the same actions and functions as text/template, but it escapes every value according to where it lands: in text, in an attribute, in a URL, in JavaScript, in CSS.
Common misunderstanding: "I will use text/template and call html.EscapeString myself." Context matters: the right escaping inside an href is different from inside a script, and the package tracks that context for you. Doing it by hand is how XSS is born.
Definition: the package documentation describes a contextual auto-escaper; a value of type template.HTML is trusted and not escaped, so converting user input to it is a vulnerability. Layouts, caching, forms, CSRF fields and flash messages are the subject of html/template: Layouts, Caching, Forms, Flash Messages; the threat model is in OWASP Top 10.
1 data := "<script>alert(1)</script>"
2 text/template {{.}} -> <script>alert(1)</script> (dangerous in a browser)
3 html/template {{.}} -> <script>alert(1)</script>
4 html/template <a href="{{.URL}}"> with "javascript:alert(1)" -> href="#ZgotmplZ"Real scenario: a web page, an HTML e-mail, an admin panel. Plain-text e-mail parts, shell scripts and YAML are the right place for text/template.
| Package | Escapes | Use for |
|---|---|---|
text/template | Nothing | Plain text, config files, code generation, CLI output |
html/template | HTML, attribute, URL, JS, CSS contexts | Anything a browser renders |
Fix / how to use it: import html/template for HTML, never mix the two packages in one handler, and never convert untrusted strings to template.HTML.
regexp: RE2 syntax, groups and replacement Must-know
In plain words: the regexp package finds and rewrites text by pattern. It is deliberately smaller than PHP's PCRE: no lookahead, lookbehind or backreferences, but it can never take exponential time.
Common misunderstanding: "A regex is the right tool because it is shorter." For a prefix, a suffix or a fixed substring, strings is shorter, faster and safer. And "my pattern works in PHP so it works in Go" fails on the first (?=...).
Definition: the package documentation says its syntax is "the syntax accepted by RE2", that the implementation "is guaranteed to run in time linear in the size of the input", and that it works on UTF-8 text (each byte of an invalid sequence is treated as utf8.RuneError). regexp.Compile returns (*Regexp, error); MustCompile panics, intended for package-level variables. A *Regexp is safe for concurrent use. Method names follow Find(All)?(String)?(Submatch)?(Index)?: MatchString, FindString, FindStringSubmatch, FindAllString, FindAllStringSubmatch, ReplaceAllString (expands $1 and ${name}), ReplaceAllLiteralString, ReplaceAllStringFunc, Split, SubexpNames, SubexpIndex. Named group syntax is (?P<name>re) (and (?<name>re) in newer Go). Flags (?i), (?s), (?m), (?U). Perl classes \d \w \s are ASCII-only; use \p{L}, \p{Arabic} for Unicode. No lookaround and no backreferences: they are rejected with errors.
1 regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
2 re.FindStringSubmatch("on 2025-08-12") -> ["2025-08-12" "2025" "08" "12"]
3 re.SubexpIndex("month") -> 2
4 re.ReplaceAllString(s, "${day}/${month}/${year}") -> "12/08/2025"
5 regexp.Compile("(?=foo)bar") -> error parsing regexp: invalid or unsupported Perl syntax: `(?=`
6 regexp.Compile(`(a)\1`) -> error parsing regexp: invalid escape sequence: `\1`
7 regexp.Compile("(abc") -> error parsing regexp: missing closing ): `(abc`
8 regexp.MustCompile("(abc") -> panic: regexp: Compile(`(abc`): error parsing regexp: missing closing ): `(abc`Real scenario: extracting key=value pairs from logfmt lines; validating a slug or a phone format; redacting card-number-like runs in logs; routing paths in a legacy gateway; finding TODO(user) comments in a code base.
| Method | Returns | Use |
|---|---|---|
MatchString(s) | bool | Does it match anywhere |
FindString(s) | first match text | One match |
FindStringSubmatch(s) | match plus groups | Parse one record |
FindAllString(s, n) | all matches (n<0 for all) | Tokenise |
FindAllStringSubmatch(s, n) | slice of match plus groups | Parse many records (logfmt) |
FindStringIndex(s) | byte offsets | Highlight, cut |
ReplaceAllString(s, repl) | new string, $1 expands | Reformat |
ReplaceAllLiteralString | no expansion | Replace with text containing $ |
ReplaceAllStringFunc(s, f) | callback per match | Computed replacement |
SubexpNames, SubexpIndex | group names | Named groups |
Longest() | switch to leftmost-longest | POSIX semantics |
Fix / how to use it: the re package parses dates with named groups, logfmt with FindAllStringSubmatch, doubles numbers with ReplaceAllStringFunc, and pins each RE2 rejection above with a test.
// Package re shows regexp usage: package-level MustCompile, named groups,
// FindAll and ReplaceAllStringFunc, plus what RE2 refuses to do.
package re
import (
"regexp"
"strings"
)
// Compiled once at program start; compiling inside a handler repeats the
// parse and compile work on every request.
var (
reDate = regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})`)
reLogKV = regexp.MustCompile(`(\w+)=("[^"]*"|\S+)`)
reDigits = regexp.MustCompile(`\d+`)
reSpaces = regexp.MustCompile(`\s+`)
)
// Date is the named groups of an ISO date.
type Date struct{ Year, Month, Day string }
// ParseDate returns the named groups of the first date in s.
func ParseDate(s string) (Date, bool) {
m := reDate.FindStringSubmatch(s)
if m == nil {
return Date{}, false
}
return Date{
Year: m[reDate.SubexpIndex("year")],
Month: m[reDate.SubexpIndex("month")],
Day: m[reDate.SubexpIndex("day")],
}, true
}
// ParseLogfmt extracts key=value pairs with FindAllStringSubmatch.
func ParseLogfmt(line string) map[string]string {
out := map[string]string{}
for _, m := range reLogKV.FindAllStringSubmatch(line, -1) {
out[m[1]] = strings.Trim(m[2], `"`)
}
return out
}
// DoubleNumbers replaces every run of digits by twice its value, using a
// callback. It only handles small numbers; it exists to show the callback form.
func DoubleNumbers(s string) string {
return reDigits.ReplaceAllStringFunc(s, func(d string) string {
n := 0
for _, c := range d {
n = n*10 + int(c-'0')
}
return itoa(n * 2)
})
}
func itoa(n int) string {
if n == 0 {
return "0"
}
var b [20]byte
i := len(b)
for n > 0 {
i--
b[i] = byte('0' + n%10)
n /= 10
}
return string(b[i:])
}
// Collapse squeezes runs of white space into one space. strings.Fields +
// Join does the same job without a regexp and is faster.
func Collapse(s string) string { return reSpaces.ReplaceAllString(strings.TrimSpace(s), " ") }
// CollapseNoRegexp is the strings-only version.
func CollapseNoRegexp(s string) string { return strings.Join(strings.Fields(s), " ") }
// Reformat swaps day and month using $name references in the template.
func Reformat(s string) string {
return reDate.ReplaceAllString(s, "${day}/${month}/${year}")
}
// Compile exposes regexp.Compile so tests can show RE2 rejections.
func Compile(expr string) error {
_, err := regexp.Compile(expr)
return err
}Regexp performance: precompile, avoid backtracking, prefer strings Important
In plain words: compiling a pattern costs far more than matching with it, so compile once when the program starts. And because Go's engine never backtracks, no input can make one request hang for minutes the way a nested-quantifier pattern can in PCRE.
Common misunderstanding: "Linear time means fast." It means no explosion. The Go engine is slower than PCRE JIT on many patterns and slower than strings by a large factor; a regexp in a hot loop is still a cost.
Definition: PCRE-style engines try alternatives and retreat when one fails (backtracking); the worst case for a pattern like ^(a+)+$ on aaaa...b is exponential, the classic ReDoS vulnerability. RE2 simulates all alternatives together, so the time is proportional to pattern size times input size. The price: lookaround and backreferences cannot be implemented that way and are not supported.
1 input = "a" x 5000 + "b" pattern = ^(a+)+$
2 PCRE-style backtracking -> catastrophic: seconds to years depending on length
3 Go regexp (RE2) -> 'no match' in milliseconds (test asserts < 2 s)
4 compile inside handler -> 800 ns, 26 allocations per request (measured, Apple silicon)
5 precompiled at package level -> 49 ns, 0 allocations per match
6 regexp collapse white space -> 5629 ns vs strings.Fields+Join 736 ns (measured)Real scenario: an API that validated user input with a nested-quantifier regexp and went down under a single crafted request in a backtracking language, a classic outage story; here the same pattern is merely slow-ish. A handler that compiled MustCompile inside the function and showed up at the top of a CPU profile.
| Situation | Choice | Reason |
|---|---|---|
| Fixed prefix, suffix, substring | strings.HasPrefix, HasSuffix, Contains | No engine at all |
| Split on separators or white space | strings.Fields, Split, Cut | 5 to 8 times faster than a regexp in the benchmark above |
| Several fixed replacements | strings.NewReplacer | One pass |
| Structured pattern with groups | regexp precompiled | Clear and linear time |
| Needs lookahead or backreference | Hand-written parser, or a PCRE port with a timeout | RE2 refuses the pattern |
| Untrusted pattern from a user | regexp (still bound the input length) | Linear time protects you; memory still grows with pattern size |
Fix / how to use it: declare patterns as package-level var x = regexp.MustCompile(...); the invalid pattern fails at start-up, which is what you want. Benchmarks BenchmarkCompileEachTime and BenchmarkCollapse in the re package produced the numbers above.
Unicode normalization and case folding Important
In plain words: the same visible text can be stored as different bytes. é can be one code point or e plus a combining accent. Two users type the "same" name and == says they differ. Normalization picks one canonical form; case folding makes comparison case-insensitive in a Unicode-correct way.
Common misunderstanding: "strings.ToLower(a) == strings.ToLower(b) is a correct case-insensitive comparison." It misses normalization differences, and it is wrong for some languages (Turkish dotted and dotless i, German ß).
Definition: Unicode defines four normalization forms in UAX #15: NFC (canonical composition, the usual storage form), NFD (decomposed), NFKC and NFKD (compatibility forms that also fold things like the fi ligature U+FB01 or full-width letters; lossy, use for search keys not for storage). The package golang.org/x/text/unicode/norm implements them (norm.NFC.String(s), norm.NFC.IsNormalString, streaming norm.Iter and Reader). golang.org/x/text/cases provides language-aware Upper, Lower, Title and Fold (full case folding: Straße and STRASSE fold to the same string). strings.EqualFold uses only simple folding: it equates K (Kelvin sign U+212A) and k, but not ß and SS, and not e plus U+0301 with é.
1 composed := "é" // U+00E9, 2 bytes
2 decomposed := "e" + U+0301 // 3 bytes
3 composed == decomposed // false, though both display as é
4 norm.NFC.String(decomposed) == composed // true
5 FormCounts(decomposed): NFC=1 NFD=2 NFKC=1 NFKD=2 runes
6 cases.Upper(language.Turkish).String("i") -> U+0130 (dotted capital I)
7 cases.Fold().String("Straße") == cases.Fold().String("STRASSE") // true
8 strings.EqualFold("Straße", "STRASSE") // falseReal scenario: login names and e-mail local parts compared across macOS (which prefers decomposed file names) and Linux; a unique index on usernames that lets café be registered twice; search that must find Straße with strasse; a Turkish user whose title is upper-cased to I instead of İ.
| Form | Meaning | Use |
|---|---|---|
| NFC | Composed canonical | Store and compare identifiers |
| NFD | Decomposed canonical | Strip accents (drop marks of category Mn) |
| NFKC | Composed with compatibility folding | Search keys, loose matching |
| NFKD | Decomposed with compatibility folding | Aggressive search keys |
cases.Fold() | Full case folding | Case-insensitive keys |
cases.Upper(tag) / Lower(tag) / Title(tag) | Language-aware mapping | User-visible text |
strings.EqualFold | Simple folding, no normalization | Quick ASCII-mostly comparison |
Fix / how to use it: normalize to NFC when text enters the system, store a derived search_key (NFKC plus fold) next to the display value, and index the key. PostgreSQL 13 and later also has normalize(text, NFC) in SQL (documented under string functions) when the server encoding is UTF8.
Persian and Arabic text: ZWNJ, look-alike letters, digits and bidi Must-know
In plain words: Persian text has four traps that ASCII programmers never meet: the invisible half-space (ZWNJ) that is part of correct spelling, Arabic letters that look identical to Persian ones, three sets of digits, and right-to-left display that mixes with left-to-right text.
Common misunderstanding: "Two Persian strings that look equal are equal." A user who types علي with the Arabic keyboard's yeh (U+064A) and one who types علی with the Persian yeh (U+06CC) produce identical-looking, different-byte strings. Likewise میخواهم (with ZWNJ) and میخواهم (without) are different strings for the same word.
Definition: ZWNJ is U+200C, three bytes in UTF-8 (E2 80 8C), one rune, zero width: it prevents joining between letters (the Persian half-space). Arabic yeh U+064A and kaf U+0643 versus Persian yeh U+06CC and keheh U+06A9; Persian digits U+06F0..U+06F9 versus Arabic-Indic U+0660..U+0669 versus ASCII 0..9. Directional marks: RLM U+200F, LRM U+200E, isolates RLI U+2067 and PDI U+2069 (the Unicode bidirectional algorithm is UAX #9). unicode.Is(unicode.Arabic, r) classifies scripts. golang.org/x/text/language parses BCP 47 tags and matches Accept-Language headers (language.NewMatcher, ParseAcceptLanguage). Go does not reorder text for display; the terminal, browser or PDF renderer applies the bidi algorithm, so your job is to store clean logical-order text and wrap embedded fragments in isolates when mixing directions.
1 user A types: U+0639 U+0644 U+064A (ends with Arabic yeh)
2 user B types: U+0639 U+0644 U+06CC (ends with Persian yeh) -> look identical
3 A == B -> false; len(A) == len(B) == 6
4 NormalizePersian(A) == B -> true
5 "می" + ZWNJ + "خواهم" vs "میخواهم" -> different; SearchKey() drops ZWNJ so both match
6 NormalizePersian("۱۲۳ ٤٥٦") -> "123 456"
7 Match("fa-IR,fa;q=0.9,en;q=0.5") -> "fa" Match("de") -> "en" (fallback)Real scenario: a Persian e-commerce search where ي versus ی returns no results; phone numbers pasted with Persian digits that fail Atoi; an invoice PDF where an English product code inside a Persian sentence renders in the wrong order until wrapped in an isolate; a username unique constraint bypassed with a look-alike letter (a spoofing vector).
| Problem | Symptom | Fix |
|---|---|---|
| Arabic yeh/kaf versus Persian yeh/keheh | Search misses, duplicate accounts | Map to the Persian letters before comparing |
| ZWNJ present or absent | میخواهم not found by میخواهم | Keep ZWNJ in display text, drop it in the search key |
| Persian and Arabic-Indic digits | strconv.Atoi syntax error | Map digits to ASCII at input |
| Tatweel U+0640, directional marks | Strings differ invisibly | Strip them from keys |
| Mixed direction in one line | Numbers or Latin words jump around | Wrap fragments in RLI/LRI and PDI |
| Language choice | Wrong UI language | language.NewMatcher with Accept-Language |
| Non-letter case | ToUpper has no effect on Persian | Case mapping is a no-op; fold only Latin parts |
Fix / how to use it: the persian package below is the whole pipeline: NormalizePersian (NFC plus letter and digit mapping plus mark stripping, ZWNJ kept), SearchKey (adds ZWNJ removal and case folding), FormCounts, GraphemeSafeTruncate (cuts at a normalization segment so a base letter keeps its marks), TitleFor/UpperFor and Match.
// Package persian collects the string problems Persian and Arabic text
// raise: look-alike letters, digits, ZWNJ, bidi controls, normalization and
// case folding.
package persian
import (
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"golang.org/x/text/unicode/norm"
)
// Code points written as numbers so that invisible and look-alike characters
// are visible in the source.
const (
ZWNJ = rune(0x200C) // zero width non-joiner: half-space
ZWJ = rune(0x200D)
ArabicYeh = rune(0x064A) // looks like the Persian letter but is a different letter
PersianYeh = rune(0x06CC)
ArabicKaf = rune(0x0643)
PersianKeh = rune(0x06A9)
RLM = rune(0x200F) // right-to-left mark
LRM = rune(0x200E)
RLI = rune(0x2067) // right-to-left isolate
PDI = rune(0x2069) // pop directional isolate
TatweelRune = rune(0x0640)
)
var digitFix = strings.NewReplacer(
// Extended Arabic-Indic digits (Persian) to ASCII.
string(rune(0x06F0)), "0", string(rune(0x06F1)), "1", string(rune(0x06F2)), "2",
string(rune(0x06F3)), "3", string(rune(0x06F4)), "4", string(rune(0x06F5)), "5",
string(rune(0x06F6)), "6", string(rune(0x06F7)), "7", string(rune(0x06F8)), "8",
string(rune(0x06F9)), "9",
// Arabic-Indic digits to ASCII.
string(rune(0x0660)), "0", string(rune(0x0661)), "1", string(rune(0x0662)), "2",
string(rune(0x0663)), "3", string(rune(0x0664)), "4", string(rune(0x0665)), "5",
string(rune(0x0666)), "6", string(rune(0x0667)), "7", string(rune(0x0668)), "8",
string(rune(0x0669)), "9",
)
// NormalizePersian prepares user text for search or comparison: Unicode NFC,
// Arabic letter variants mapped to the Persian ones, digits to ASCII, and
// tatweel and directional marks removed. ZWNJ is kept because it is part of
// correct spelling.
func NormalizePersian(s string) string {
s = norm.NFC.String(s)
s = strings.Map(func(r rune) rune {
switch r {
case ArabicYeh:
return PersianYeh
case ArabicKaf:
return PersianKeh
case TatweelRune, RLM, LRM, RLI, PDI:
return -1 // drop
}
return r
}, s)
return digitFix.Replace(s)
}
// SearchKey additionally drops ZWNJ and folds case so "میخواهم" and
// "میخواهم" find each other.
func SearchKey(s string) string {
s = NormalizePersian(s)
s = strings.ReplaceAll(s, string(ZWNJ), "")
return cases.Fold().String(s)
}
// FormCounts returns the rune counts of the four Unicode normalization forms.
func FormCounts(s string) map[string]int {
count := func(f norm.Form) int { return len([]rune(f.String(s))) }
return map[string]int{
"NFC": count(norm.NFC), "NFD": count(norm.NFD),
"NFKC": count(norm.NFKC), "NFKD": count(norm.NFKD),
}
}
// GraphemeSafeTruncate cuts at most n runes but never between a base
// character and the combining marks that follow it.
func GraphemeSafeTruncate(s string, n int) string {
var it norm.Iter
it.InitString(norm.NFC, s)
count, end := 0, 0
for !it.Done() {
seg := it.Next() // one normalization segment: base + following marks
r := utf8.RuneCount(seg)
if count+r > n {
break
}
count += r
end = it.Pos() // byte offset in the ORIGINAL string
}
return s[:end]
}
// TitleFor applies language-aware title casing: Turkish keeps dotted i.
func TitleFor(tag, s string) string {
return cases.Title(language.MustParse(tag)).String(s)
}
// UpperFor applies language-aware upper casing.
func UpperFor(tag, s string) string {
return cases.Upper(language.MustParse(tag)).String(s)
}
// IsRTL reports whether the first strong character of s is right-to-left.
// It is a simplified version of the bidi algorithm's first rule (P2/P3).
func IsRTL(s string) bool {
for _, r := range s {
switch {
case unicode.Is(unicode.Arabic, r), unicode.Is(unicode.Hebrew, r):
return true
case unicode.IsLetter(r):
return false
}
}
return false
}
// IsolateRTL wraps text in a right-to-left isolate so it renders correctly
// even when pasted into a left-to-right sentence.
func IsolateRTL(s string) string { return string(RLI) + s + string(PDI) }
// Match picks the best supported language for an Accept-Language header.
func Match(header string) string {
supported := []language.Tag{language.English, language.Persian, language.Arabic}
matcher := language.NewMatcher(supported)
tags, _, _ := language.ParseAcceptLanguage(header)
_, idx, _ := matcher.Match(tags...)
return supported[idx].String()
}Conversions and allocations; unsafe.String Good to know
In plain words: turning a string into a byte slice, or the reverse, normally copies the data, because strings are immutable and slices are not. The compiler skips the copy when it can prove nobody will observe the difference; unsafe lets you skip it by promising to behave.
Common misunderstanding: "[]byte(s) is free." It allocates and copies len(s) bytes unless the compiler optimises it. And "unsafe.String is a speed-up I can sprinkle around": it is a contract, and breaking the contract corrupts memory shared with other holders of the string.
Definition: the spec says converting a slice of bytes to a string yields a string whose successive bytes are the elements of the slice (a copy). The compiler avoids copies in a few patterns: m[string(b)] map lookups, string(b) == "x" comparisons, for range []byte(s), and concatenations that do not escape. unsafe.String(ptr, len), unsafe.StringData(s) and unsafe.Slice (Go 1.20) build a string or slice header over existing memory with no copy. Rules: never write through a []byte obtained from a string (the memory may be read-only), and never modify a []byte while a string made from it is in use. See the memory-model discussion in Pointers & Memory Model Basics.
1 s := strings.Repeat("x", 1024)
2 b := []byte(s) // 1 allocation, 1024 bytes copied
3 v := unsafe.Slice(unsafe.StringData(s), len(s)) // 0 allocations, aliases s
4 v[0] = 'y' // forbidden: may crash (read-only data) or corrupt every user of s
5 n := m[string(key)] // 0 allocations: compiler elides the copy
6 if string(b) == "key" {} // 0 allocationsReal scenario: a parser that must not allocate per token; a zero-copy log pipeline; bytes.Buffer.String() versus Bytes(); a hot path where profiling shows runtime.slicebytetostring at the top. If the profile does not show it, do not use unsafe.
| Conversion | Allocates | Safe |
|---|---|---|
[]byte(s), string(b) | Yes (copy), unless elided | Yes |
m[string(b)], string(b) == "lit" | No (compiler) | Yes |
unsafe.String(&b[0], len(b)) | No | Only if b is never modified afterwards |
unsafe.Slice(unsafe.StringData(s), n) | No | Only if never written |
strings.Clone(s) | Yes (one copy) | Yes; detaches from a large parent string |
Fix / how to use it: the zerocopy snippet's tests measure 1 allocation versus 0 and demonstrate that a string aliased over a byte slice changes when the slice changes, which is exactly why the contract matters.
// Package zerocopy shows the cost of string/[]byte conversions and the
// unsafe escape hatch that avoids them. Use it only when a profile says so.
package zerocopy
import "unsafe"
// CopyToBytes is the safe conversion: it allocates and copies.
func CopyToBytes(s string) []byte { return []byte(s) }
// ViewAsBytes returns a []byte that aliases the string's memory. The caller
// must never write to the result: strings are immutable and may live in
// read-only memory (a write can crash the program).
func ViewAsBytes(s string) []byte {
if s == "" {
return nil
}
return unsafe.Slice(unsafe.StringData(s), len(s))
}
// ViewAsString returns a string that aliases b. The caller must not modify b
// for as long as the string is in use.
func ViewAsString(b []byte) string {
if len(b) == 0 {
return ""
}
return unsafe.String(&b[0], len(b))
}
// Upper changes the case of ASCII letters in place on a byte slice.
func Upper(b []byte) {
for i, c := range b {
if c >= 'a' && c <= 'z' {
b[i] = c - ('a' - 'A')
}
}
}Mechanics
Exact messages and what they mean Must-know
| Message | Where | Meaning |
|---|---|---|
strconv.Atoi: parsing "12a": invalid syntax | strconv | *NumError with Err == ErrSyntax |
strconv.Atoi: parsing "999...": value out of range | strconv | ErrRange; the returned value is the clamped maximum |
%!d(string=hi) | fmt | Verb does not fit the argument type |
hi%!(EXTRA string=guys) | fmt | More arguments than verbs |
hi%!d(MISSING) | fmt | More verbs than arguments |
%!(BADWIDTH), %!(BADPREC), %!(BADINDEX), %!(NOVERB) | fmt | Bad * argument, bad .*, bad [n], trailing % |
%!s(PANIC=bad) | fmt | A String or Error method panicked |
strings: illegal use of non-zero Builder copied by value | strings.Builder | A used Builder was copied |
template: bad:1: unclosed action | text/template | Parse error with name and line |
template: fn:1: function "nosuch" not defined | text/template | Function not in FuncMap at parse time |
template: x:1:2: executing "x" at <.Missing>: can't evaluate field Missing in type ... | text/template | Exec-time error: no such field |
map has no entry for key "b" | text/template | missingkey=error |
error parsing regexp: invalid or unsupported Perl syntax: (?=`` | regexp | Lookahead rejected |
error parsing regexp: invalid escape sequence: \1`` | regexp | Backreference rejected |
error parsing regexp: missing closing ): ... | regexp | Unbalanced group |
panic: regexp: Compile((abc): error parsing regexp: ... | regexp.MustCompile | Panic at start-up for a package-level var |
cannot assign to s[0] (neither addressable nor a map index expression) | compiler | Strings are immutable |
fmt.Sprintf format %d has arg "hi" of wrong type string | go vet | printf analyzer |
Tools and flags you will use Must-know
| Command | Use |
|---|---|
go vet ./... | printf-style checks, copylocks, %w misuse (go test runs a subset automatically) |
go test -run TestX -v ./verbs | Run one test, see names |
go test -bench . -benchmem ./builder | Timing and allocations per op |
testing.AllocsPerRun(n, f) | Assert allocation counts in a unit test |
go build -gcflags=-m | See which conversions escape or allocate |
go doc fmt / go doc text/template | Read package docs offline |
gofmt -l . | Formatting check |
go test -race ./... | Race detector (templates and regexps are safe once built) |
Measured costs
All numbers below were produced by go test -bench from the builder and re packages on an Apple-silicon laptop with Go 1.27.4 (module directive go 1.24); they are real, they vary by machine, and only their ratios matter.
| Benchmark | Time per op | Bytes per op | Allocations per op |
|---|---|---|---|
Concat 256 parts with += | 16357 ns | 165729 | 255 |
Concat with Builder and Grow | 891 ns | 1280 | 1 |
Concat with bytes.Buffer | 1078 ns | 5312 | 7 |
Concat with strings.Join | 1255 ns | 1280 | 1 |
| Collapse white space, regexp | 5629 ns | 1390 | 9 |
Collapse white space, Fields + Join | 736 ns | 1376 | 2 |
MustCompile inside the loop plus match | 800 ns | 2813 | 26 |
| Precompiled match | 49 ns | 0 | 0 |
Solving the classic problems
Problem: truncate user text safely
| Solution | How | Advantage | Cost or limitation |
|---|---|---|---|
Slice bytes s[:n] | Direct | O(1) | Can split a rune, produces invalid UTF-8 |
| Cut at rune boundary | range and slice at offset | Valid UTF-8 | O(n) |
| Cut at grapheme boundary | norm.Iter segments or a grapheme library | No broken accents or emoji sequences | Slower, extra dependency for emoji |
| Reject over-long input | Validate rune count at the edge | Simplest contract | User sees an error instead of truncation |
Use TruncateRunes or GraphemeSafeTruncate from the snippets, and store the original text, not the truncated one.
Problem: unique, searchable names across Persian keyboards
Store both the display value and a normalized key, enforce uniqueness on the key, and compute the key in one function in Go so every code path agrees.
-- display text is kept as typed; the key is what is compared and indexed
CREATE TABLE customers (
id bigserial PRIMARY KEY,
name text NOT NULL,
name_key text NOT NULL -- persian.SearchKey(name), computed in the application
);
CREATE UNIQUE INDEX customers_name_key_uq ON customers (name_key);
-- PostgreSQL 13+ can also normalize in SQL (server encoding must be UTF8)
SELECT normalize(U&'\0065\0301', NFC) = U&'\00E9' AS composed_equal;Pros: one rule, enforced by the database. Cons: changing the key function means re-computing the column, so version it (name_key_v) before you need to.
Problem: parse log lines and key=value pairs
| Need | Tool | Note |
|---|---|---|
Fixed key=value | strings.Cut | No regexp needed |
| Quoted values with spaces | regexp with FindAllStringSubmatch | ParseLogfmt in the snippet |
| Large files | bufio.Scanner plus strings.Cut per line, or strings.Lines (Go 1.24) | See Files, Directories, Paths, Temp Files, bufio & embed |
| Structured logging | log/slog with attributes | See CLI Flags, Subcommands, Environment Variables & Logging |
Problem: generate a mail body or config file
Parse at start-up with template.Must, pass a typed struct (not map[string]any), execute into a buffer, test with golden strings, and use missingkey=error when data comes from a map. For HTML mail use html/template.
Problem: a regexp became the hot spot
- Move
MustCompileto package level. - Replace with
stringsfunctions when the pattern is a prefix, suffix, fixed text or white-space split. - Anchor the pattern (
^...$) so the engine can reject early; a literal prefix is searched with a fast path. - Use
Match/MatchStringwhen you do not need the text; useFind...Indexand slice yourself when you do. - Measure with
go test -bench -benchmembefore and after.
Problem: PHP preg_* pattern uses lookahead
| PCRE feature | RE2 alternative |
|---|---|
Positive lookahead (?=x) | Match with the context and use a capture group |
Negative lookahead (?!x) | Match, then test the group in code |
Lookbehind (?<=x) | Capture the prefix and drop it |
Backreference \1 | Compare two groups in code after matching |
| Possessive quantifiers, atomic groups | Not needed: no backtracking |
| Password complexity in one regexp | Several small checks (strings.ContainsFunc, unicode classes) |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Count "characters" for a limit | utf8.RuneCountInString | Grapheme library for emoji and combining marks | Bytes are wrong, runes are mostly right |
| Build a string in a loop | strings.Builder with Grow | fmt.Fprintf(&b, ...) | One allocation |
| Write straight to a response | fmt.Fprintf(w, ...) or a template | Buffer if all-or-nothing | No intermediate string |
| Parse a number from input | strconv.Atoi/ParseInt | Check *NumError | Exact error text |
| Money amounts | integers in minor units | ParseInt | Floats lose cents |
| Compare identifiers | NFC then cases.Fold | Store a key column | Users type differently |
| Plain-text output | text/template | template.Must at start-up | Fail fast |
| HTML output | html/template | Never template.HTML on user input | Contextual escaping |
| Simple search | strings | Cut, Fields, HasPrefix | Faster and clearer |
| Pattern with groups | regexp at package level | Named groups | Linear time |
| Pattern needing lookaround | Parse by hand | Small state machine | RE2 refuses |
| Hot path conversion | unsafe.String only after profiling | A unit test with AllocsPerRun | Contract risk |
In architecture: from a single process to a distributed system
Monolith: one process, one database
All text rules live in one place. Parse templates and compile regexps at start-up into package-level values, validate UTF-8 and normalize to NFC at the HTTP boundary, and keep money as integers. Example: a Laravel-style admin in Go renders HTML with html/template parsed once from an embedded filesystem, formats rows with fmt.Fprintf(w, "%-12s %8.2f\n", ...) for CSV-like exports, and compares usernames through one SearchKey function.
Modular monolith and multiple databases
Modules must agree on the normal form of text that crosses their boundary. If the accounts module stores NFC and the search module indexes NFKC keys, the contract is "the module that owns the data exposes a Key() function". Each database gets its own collation rules (PostgreSQL collations, MySQL utf8mb4_unicode_ci), so never rely on the database's = for Unicode-correct matching across stores; compare keys.
Microservices
Text crosses services as JSON (always UTF-8 by spec; the encoder replaces invalid bytes) or Protocol Buffers (string fields must be valid UTF-8, binary data uses bytes; see gRPC & Protobuf in Go). Normalize once at the edge so downstream services do not each re-normalize, and agree on a locale header (Accept-Language, matched with language.NewMatcher) that travels with the request, as with any other context value (see context). A mailer service owns its templates and receives data, not pre-rendered text, so translators and designers can change them without redeploying the callers. Log lines carry request IDs, and structured fields rather than interpolated strings; see Observability.
Distributed data: replicas, caches, collation and encodings
Keys in caches and shard routers must be byte-identical across all nodes: hash the normalized, folded key, never the display string, or café composed and decomposed land on different shards and miss the cache. A consistent hash over unnormalized text silently splits one user into two. Replicas of a database with different collation or ICU versions can order text differently (a known source of corrupt indexes after an OS upgrade in PostgreSQL), so index on a normalized key column that Go computes. Messages in queues should carry text as UTF-8 with the schema stating the normal form.
Scaling path: 1x, 10x, 100x
| Load | Text concern | Action |
|---|---|---|
| 1x | Correctness | fmt and regexp freely, vet in CI, template.Must at start-up |
| 10x | Allocation rate in formatting and parsing | Builder with Grow, AppendInt into reused buffers, precompiled regexps, strings.Cut instead of regexp |
| 100x | Hot-path conversions and logging volume | Profile first; sync.Pool of buffers, zero-copy parsing with an explicit contract, slog with typed attributes, pre-rendered templates cached per locale, search keys precomputed at write time |
Lab
Everything runs on the host with Go only. Outputs marked "real" were captured during authoring (Go 1.27.4, module go 1.24, golang.org/x/text v0.22.0).
cd docs/snippets/go/strings-runes-formatting-templates/go
gofmt -l . && go vet ./... && go test -race ./...
go run ./demo- Bytes versus runes.
go run ./demo. Real output:"café" bytes=5 runes=4 valid=true,"سلام" bytes=8 runes=4 valid=true,"a\xffb" bytes=3 runes=3 valid=false, thenoffset=0 rune=U+00E9 width=2,offset=2 rune=U+4E16 width=3,offset=5 rune=U+FFFD width=1for the input of an accented letter, a CJK character and a bad byte. - Look-alike letters. The same program prints
false true: the Arabic-yeh and Persian-yeh strings differ, andNormalizePersianmakes them equal. It then printsmap[NFC:1 NFD:2 NFKC:1 NFKD:2]foreplus U+0301. - Template. The program ends with the rendered receipt (real output):
Order #7 for ADA,00 A-1 x2 12.50,01 B-22 x1 0.99,Note: leave at door,regular order,Total: 25.99. - vet catches format bugs. Create a file with
fmt.Printf("%d\n", "hi"),fmt.Println("done %d", 3)andfmt.Sprintf("%w", err), thengo vet ./.... Real output:format %d has arg "hi" of wrong type string,call has possible Printf formatting directive %d,fmt.Sprintf does not support error-wrapping directive %w. - Allocation counts.
go test -run 'TestBuilderAllocatesOnce|TestAppendRow|TestConversionAllocations' -v ./...passes: the builder allocates once,AppendRowzero times,[]byte(s)once and the unsafe view zero times. - Benchmarks.
go test -run xxx -bench . -benchmem ./builder ./re. Real output is the table in Measured costs; on your machine the ratios should match, the absolute numbers will not. - ReDoS test.
go test -run TestNoCatastrophicBacktracking -v ./repasses in milliseconds. Try the same pattern^(a+)+$with a 5000-character input in a backtracking engine such as PHP's PCRE withpcre.backtrack_limitraised (expected, not run: the preg call returnsfalseandpreg_last_error()reportsPREG_BACKTRACK_LIMIT_ERROR). - Postgres normalization (expected, not run). In
psql:SELECT normalize(U&'\0065\0301', NFC) = U&'\00E9';expectedt;SELECT 'é' = U&'\0065\0301';expectedf.
Common misconceptions
| Belief | Reality |
|---|---|
len(s) is the number of characters | It is the number of bytes |
s[i] is a character | It is a byte |
| Strings are always valid UTF-8 | Only literals are; input may contain any bytes |
range over a string gives bytes | It gives runes and byte offsets |
rune is a separate type | It is an alias for int32 |
+= in a loop is fine | Quadratic copying; use strings.Builder |
strings.Split(s, " ") splits words | It splits on one space only; use Fields |
Atoi accepts spaces and 1e3 | Decimal digits with an optional sign only |
%w works in Printf | Only in fmt.Errorf |
%v never leaks secrets | It prints whatever String/Error returns |
text/template escapes HTML | Only html/template does |
| A template that parses will run | Field errors appear at execute time |
| Go regexp supports lookahead | RE2 does not; it rejects the pattern |
| Linear time means regexp is fast | It is slower than strings for simple jobs |
strings.ToLower(a) == strings.ToLower(b) compares text correctly | Needs normalization and full folding for Unicode |
| Two Persian words that look equal are equal | Arabic letters, ZWNJ and digit sets differ |
Cheat sheet
| Topic | What to remember |
|---|---|
| String | Immutable bytes, header of pointer and length |
len, s[i] | Bytes |
range s | Runes with byte offsets; bad byte gives U+FFFD, width 1 |
rune | int32 code point; []rune(s) allocates |
| Count characters | utf8.RuneCountInString; graphemes need a library |
| Validate | utf8.ValidString, repair with strings.ToValidUTF8 |
| Split one separator | strings.Cut |
| Split words | strings.Fields |
| Build text | strings.Builder plus Grow; never copy it |
| Numbers | Atoi, ParseFloat, AppendInt; check *NumError |
| Verbs | %v %+v %#v %T %q %x %p %08.3f %[1]d %*d |
| Interfaces | Stringer, GoStringer, Formatter; error before Stringer |
| Wrap errors | fmt.Errorf("...: %w", err); run go vet |
| Templates | Parse once with Must; Funcs before Parse; trim markers strip white space; missingkey=error |
| HTML | html/template, never template.HTML on input |
| Regexp | RE2, linear time, no lookaround; MustCompile at package level |
| Unicode | NFC at the edge, cases.Fold for keys, EqualFold is simple folding |
| Persian | Map Arabic yeh/kaf, digits to canonical; ZWNJ out of keys; isolates for bidi |
| Zero-copy | unsafe.String only after profiling, never mutate |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What are len("é世") and utf8.RuneCountInString("é世")? Must-know
Answer
Answer: len is 5 (2 + 3 bytes) and the rune count is 2.
2 — What does for i, r := range "a\xffb" yield? Important
Answer
Answer: (0, 'a'), (1, U+FFFD) and (2, 'b'): the invalid byte decodes as U+FFFD and the loop advances one byte.
3 — Why is s += x in a loop slow, and what replaces it? Must-know
Answer
Answer: Each step allocates a new string and copies the whole prefix, so the total work is quadratic. Use strings.Builder (with Grow if the size is known) or strings.Join.
4 — What does strconv.Atoi(" 7") return, and how do you inspect the error? Must-know
Answer
Answer: 0 and a *strconv.NumError whose Err is strconv.ErrSyntax; use errors.Is(err, strconv.ErrSyntax) or errors.As(err, &ne).
5 — What does fmt.Sprintf("%d", "hi") print, and which tool finds it before production? Must-know
Answer
Answer: %!d(string=hi). go vet (also run by go test) reports the wrong argument type.
6 — In what order does fmt consider Formatter, GoStringer, error and Stringer? Good to know
Answer
Answer: Formatter first; for %#v, GoStringer; for string-capable verbs, error and then Stringer; otherwise reflection.
7 — Why must Funcs come before Parse, and when is a missing struct field detected? Important
Answer
Answer: Function names are resolved while parsing, so an unknown name is a parse error. A missing field is only detected at Execute time.
8 — What does missingkey=error change? Important
Answer
Answer: Indexing a map with an absent key stops execution with map has no entry for key "..."; the default prints <no value>.
9 — Why does regexp.MustCompile("(?=foo)bar") panic, and what is the benefit of that restriction? Good to know
Answer
Answer: RE2 syntax has no lookahead. Dropping lookaround and backreferences lets the engine guarantee time linear in the input, so no input can cause catastrophic backtracking.
10 — Where should MustCompile calls live? Must-know
Answer
Answer: In package-level variables, so a bad pattern panics at start-up and compilation happens once, not on every request.
11 — Why are علي (Arabic yeh) and علی (Persian yeh) a problem for unique usernames? Important
Answer
Answer: They look the same but are different bytes, so == and a unique index treat them as two names. Map to one form (and normalize to NFC) before storing a key.
12 — When is unsafe.String justified? Good to know
Answer
Answer: Only when a profile shows the copy matters and you can guarantee the underlying bytes are never modified while the string is in use.
Glossary
| Term | Meaning |
|---|---|
| string | Immutable sequence of bytes, usually UTF-8 |
| immutable | Cannot be changed after creation; every edit builds a new value |
| byte | uint8; one element of a string's backing array |
| rune | int32 Unicode code point |
| code point | A number assigned to a character in Unicode, written U+0041 |
| grapheme | What a reader perceives as one character; may be several code points |
| UTF-8 | Variable-width encoding, 1 to 4 bytes per code point |
utf8.RuneError | U+FFFD, the replacement rune returned for invalid input |
RuneCountInString | Counts decoded runes in a string |
| range over string | Loop yielding byte offset and rune |
strings.Builder | Append-only string builder with a zero-copy String() |
bytes.Buffer | Growable byte buffer with read and write methods |
strings.Cut | Splits around the first separator, returns found flag |
strings.Fields | Splits on runs of white space |
strings.EqualFold | Case-insensitive equality by simple folding |
strconv | Package converting between strings and basic types |
*NumError | Error type from strconv parse failures |
fmt verb | The %x part of a format string |
| argument index | [n] in a verb that selects the nth argument |
Stringer | Interface with String() string |
GoStringer | Interface with GoString() string used by %#v |
Formatter | Interface with Format(State, rune) for full control |
%w | Verb in fmt.Errorf that wraps an error |
text/template | Package for text with actions and pipelines |
| action | Template construct between double braces |
| pipeline | Chain of commands joined by a vertical bar |
FuncMap | Map of custom functions for a template |
template.Must | Panics if a template failed to parse |
define / block | Named template declaration / declaration plus immediate call |
| whitespace trimming | Minus-sign markers inside template delimiters that remove adjacent white space |
missingkey | Template option controlling absent map keys |
html/template | Same API with contextual HTML escaping |
regexp | Regular expressions package using RE2 |
| RE2 | Linear-time regex engine and syntax family |
| backtracking | Retry strategy of PCRE-style engines; can be exponential |
| lookaround | Lookahead and lookbehind assertions; unsupported in RE2 |
| named group | (?P<name>...) capture |
| normalization | Choosing one canonical code-point sequence (NFC, NFD, NFKC, NFKD) |
| case folding | Unicode mapping for case-insensitive comparison |
x/text | golang.org/x/text: norm, cases, language and more |
| ZWNJ | Zero Width Non-Joiner U+200C, the Persian half-space |
| bidi | Bidirectional text algorithm for mixed LTR and RTL |
For PHP/Laravel developers
| PHP | Go | Difference |
|---|---|---|
strlen($s) | len(s) | Both count bytes |
mb_strlen($s, 'UTF-8') | utf8.RuneCountInString(s) | The mb_string extension is opt-in in PHP; in Go the decoding functions are in unicode/utf8 |
mb_substr, mb_strtoupper | rune loop, cases.Upper(tag) | Go's strings.ToUpper is not language-aware |
$s[0] | s[0] | Both give a byte; Go gives a byte number, PHP a one-byte string |
sprintf('%05.1f', $x) | fmt.Sprintf("%05.1f", x) | Similar verbs; Go adds %v, %+v, %T, %q; PHP %1$s equals Go %[1]s |
intval("12a") returns 12 | strconv.Atoi("12a") is an error | Go never guesses |
preg_match (PCRE) | regexp (RE2) | No lookaround, no backreferences; linear time instead of pcre.backtrack_limit |
| Blade echo statements escape by default | html/template escapes by context | text/template does not escape |
Normalizer::normalize() (intl) | norm.NFC.String(s) | Same four forms |
$s = "caf" . "\u{e9}";
strlen($s); // 5, bytes
mb_strlen($s); // 4, characters (code points)
mb_strtoupper($s); // "CAFÉ" with the mb_string extension
sprintf('%-10s|%08.3f', 'apple', 3.14159);
preg_match('/(?<=a)b/', 'ab'); // lookbehind works in PCRE; invalid in Go regexp
preg_match('/^(a+)+$/', str_repeat('a', 5000) . 'b'); // false, PREG_BACKTRACK_LIMIT_ERRORIn Go the same lines are len(s), utf8.RuneCountInString(s), cases.Upper(language.French).String(s), fmt.Sprintf("%-10s|%08.3f", "apple", 3.14159) and a regexp that must be rewritten without lookbehind. The habit to change: in PHP you reach for mb_* once you notice a bug; in Go you decide, at each boundary, whether a value is bytes, runes or characters, and the compiler plus go vet hold you to it.
References
- The Go Programming Language Specification: string types, conversions,
forwithrangeover strings (read for Go 1.25) - Strings, bytes, runes and characters in Go: the model behind this chapter
- Text normalization in Go: NFC, NFD,
norm - Effective Go: printing and strings
- Go FAQ
- Go Code Review Comments: error strings and naming
- fmt package documentation (Go 1.25.0 source, doc.go): verbs, flags, error strings
- fmt print.go (Go 1.25.0):
%wrules - text/template package documentation (Go 1.25.0): actions, trim markers
- text/template options (Go 1.25.0):
missingkey - html/template package documentation (Go 1.25.0): contextual escaping
- regexp package source (Go 1.25.0): RE2, linear time, method names
- regexp/syntax documentation (Go 1.25.0): the supported syntax
- Google RE2 syntax wiki: what RE2 supports and omits
- strconv documentation source (Go 1.25.0) and atoi.go:
NumError - strings.Builder source (Go 1.25.0): copy check
- unicode/utf8 source (Go 1.25.0)
- Go 1.24 release notes: iterator functions in
stringsandbytes - Go 1.25 release notes:
regexp/syntax\pnames - golang.org/x/text repository:
unicode/norm,cases,language(read at v0.22.0) - Unicode UAX #15: Normalization Forms
- Unicode UAX #9: Bidirectional Algorithm
- PostgreSQL string functions:
normalize - PHP mb_strlen, sprintf, preg_match