Zero-copy string to []byte conversion via unsafe in Go
WHAT IT TESTS: Go memory layout and unsafe trade-offs. OUTLINE: use unsafe.StringData/Slice (or reflect headers) to alias the string's bytes without copying; assumes shared backing array; risk is mutating an immutable string.
WHAT IT TESTS: whether you understand Go's string and slice memory layout and the dangers of aliasing them. ANSWER OUTLINE: a normal []byte(s) copies; in hot paths like high-throughput parsing you avoid the copy by aliasing the same backing array via unsafe.Slice(unsafe.StringData(s), len(s)) on modern Go. The assumption is that string and slice share a pointer+len layout. The critical risk is that strings are immutable, so you must never write through the resulting slice, and you must keep the source alive. RED FLAG: mutating the bytes.
Read the original → interview
- #go
- #unsafe
- #zero-copy
- #performance
- #memory-layout
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.