Contents
Dig101: dig more, simplify more, know more.
Strings look simple. They mostly are—start with what the compiler does for +.
0x01 How + is lowered
1 | s1 := "x" |
go tool compile -m folds literal runs:
1 | $ go tool compile -m plus.go |
Assembly (-S | grep concat):
1 | $ go tool compile -S plus.go|grep concat |
Pipeline:
- Fold constant string fragments at compile time (
"y" + "x" + "z"→"yxz"). - Pass remaining operands to
concatstringN/concatstrings. - Arity 2–5 →
concatstring2…concatstring5; more → sliceconcatstrings. - Total length < 32 → stack
tmpBufto skip a heap alloc.
Call sites in the compiler and runtime:
1 | // cmd/compile/internal/gc/walk.go addstr |
0x02 String is slice-shaped
Inside concatstrings you already see slice mechanics:
1 | func concatstrings(buf *tmpBuf, a []string) string |
*(*slice)(unsafe.Pointer(&b)) = slice{p, size, size} — same pointer/len/cap as a []byte with len == cap.
0x03 Strings are immutable
1 | s:="abc" |
Local edits go through []byte or []rune:
1 | s := "ab\xe9" // UTF-8 for ab + e-acute |
0x04 Conversions
rune → string
rune is int32 (Unicode code point). Build []byte via encoderune into p.
Bounds-check hints like _ = p[1] help the compiler: bounds check elimination.
[]byte → string
Copy from slice base + length into a string header.
string → []rune
Allocate []rune, decode runes. for range over a string is like ranging []rune(string); immutability means no race checks on the source bytes.
string → []byte
Allocate and copy.
0x05 Zero-copy []byte → string
Some paths skip copying:
1 | // Compiler may optimize string(b) in map keys, compares, etc. |
Reinterpret the slice header as a string. Do not mutate b afterward—you would break immutability. strings.Builder.String() exploits this for speed.
0x06 Concat benchmarks
Short (16 B) vs long (256 B) strings, few vs many joins: concat_benchmark.
sprint/sprintf/Join builds are pre-sized lists; +, Builder, Buffer loop and append.

- Prebuilt args:
sprint≈sprintf;strings.Joinwins (usesBuilderinternally). - Looping
+: cost grows quickly with count. - Few joins:
strings.Builderbeatsbytes.Buffer; many joins the gap flips—check alloc counts.
Builder did more allocations per op in the test because Reset() drops storage:
1 | // Reset keeps backing array for reuse |
Builder forbids aliasing after String() (copyCheck). Both types benefit from one upfront Grow—see concatIterWithGrowInit in the repo.
After Grow, alloc counts drop to 1 per op and Builder leads, matching the docs.

Sample code: NewbMiao/Dig101-Go/types/string
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
