Chapter 08Data Structure InternalsPaid chapter

Strings, Bytes, and the Cost of Conversion

Separate string-conversion copying, heap allocation, and aliasing constraints.

Launch paywall

This chapter is part of the paid launch. The preview stays visible so readers can evaluate the exact scope before buying.

Included in

Core and Complete. Complete also includes the practical exam and free Go-version updates.

Preview

What this chapter teaches

Common belief

string(b) and []byte(s) are basically free — they just reinterpret the same bytes with a different type." (And its inverse, from performance folklore: "every conversion copies unless it's literally m[string(b)].")

What actually happens

the conversions copy by default, because a string is immutable and a []byte is mutable — otherwise a write through the slice would mutate a string, which the language forbids. But the compiler elides the copy wherever it can prove the copy is unobservable, and that proof now covers more than the old folklore says: string(b) used directly in a map index, comparison, switch, or range; a string(b) assigned to a local that provably stays transient (the two-step map lookup is now free); []byte(s) that is never written (zero-copy since Go 1.22); and any small non-escaping conversion, which lands in a 32-byte stack buffer. What always copies: a conversion whose result is retained (returned, stored in a map or struct) or whose bytes may be mutated.

Mechanisms covered
Short non-escaping copies can use stack storage; retained results need an independently valid lifetime.
unsafe.String requires immutable valid backing bytes for the full string lifetime; violating that contract is not a supported experiment.
benchbench + compileexperiment
One-time purchase

Unlock Chapter 08 and the rest of the course.

Core unlocks every paid chapter and lab. Complete also includes the practical exam and future Go-version updates.

Core
$49

Full course access with the complete mechanics curriculum.

All paid chapters unlocked
One-time purchase
Perfect if you want the material only
Complete
$79
Best value

Best-value launch option with the exam and free Go-version course updates.

Everything in Core
Black Belt practical exam
Free Go-version updates

No subscription or account required. Access is tied to the email entered at Stripe Checkout and can be restored by email.

Free chapter
Escape Analysis: The Compiler's Fragile Decision
Distinguish escape diagnostics from measured allocations and explain the role of lifetime and call-site visibility.
Free chapter
Maps: Swiss Tables, Growth, and Permanent Memory
Distinguish map table capacity from referenced payloads and inspect clearing and growth on Go 1.25.