Chapter 08Data Structure InternalsPaid chapter

Strings, Bytes, and the Cost of Conversion

Understand when string ↔ []byte conversions allocate, which proofs elide the copy on modern Go, and how to minimize conversion overhead.

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, Complete, and Team. 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 reinterpretations.

What actually happens

they copy by default — but the compiler elides the copy wherever it can prove it unobservable (transient uses, never-written slices, small non-escaping results), and that proof set has grown across releases. Retention and mutation are what always cost.

Mechanisms covered
What always copies: a result that is retained (map store, return, struct field) or bytes that may be mutated before the string dies.
strings.Builder avoids repeated allocation by growing a []byte buffer and converting once via unsafe at the end. unsafe.String/unsafe.SliceData (Go 1.20+) give zero-copy conversion if the immutability invariant is upheld manually.
Conversion benchmarks need >32-byte data or the stack buffer hides the cost; the lab pins every alloc count in TestConversionAllocs.
benchbench + compileexperiment
Early accessUnlock Chapter 08

Unlock Chapter 08 and the rest of the course.

Choose a plan and request access. Core unlocks the paid chapters, Complete adds the exam and free Go-version updates, and Team gives you 5 seats.

Choose a plan

Submit your email and selected plan to request launch access. No subscription. Complete also includes the practical exam and free Go-version updates.

Free chapter
Escape Analysis — The Compiler's Fragile Decision
Understand how the compiler decides between stack and heap allocation, why the decision is fragile, and how to verify it.
Free chapter
Maps — Swiss Tables, Growth, and Permanent Memory
Understand the Go 1.24+ Swiss Table map layout, why maps don't shrink, and how to design for memory reclamation.