131. mem::offset_of! — Byte Offsets Without the memoffset Crate
You need the byte offset of a field — for FFI, custom serialization, or talking to a C struct. The old answer was unsafe pointer arithmetic on a MaybeUninit, or pulling in the memoffset crate. std::mem::offset_of! is the safe, one-liner replacement.
The problem
Say you’re matching a C layout and need to know exactly where each field lives in memory:
| |
The pre-1.77 way meant either an external crate or hand-rolled unsafe:
| |
It works, but unsafe, raw pointers, and a MaybeUninit is a lot of ceremony for “where does this field start?”
The fix: mem::offset_of!
| |
No unsafe. No allocation. No instance of Header ever exists. The macro expands to a const-evaluable usize — usable inside const fn and static items.
Nested fields work too
Dot through a path of named fields and offset_of! keeps walking:
| |
Tuples and tuple structs use numeric indices:
| |
When it earns its keep
FFI bindings, custom binary parsers, kernel-style intrusive data structures, and anywhere you’d otherwise reach for memoffset. The macro is in core, so it works in no_std. Reach for it whenever you find yourself writing as *const _ as usize math.