Understanding addr_of! and addr_of_mut! - Safe Pointer Access
Rust is very strict about memory safety, especially when it comes to unaligned data. If you’ve ever worked with byte buffers, binary protocols, FFI, or #[repr(packed)] structs, you’ve probably run into an error like: “error: Reference to field of packed struct is unaligned”
This is Rust politely telling you: “Stop! Creating a reference here would be undefined behavior.”
In this article, we’ll look at why this happens and how Rust’s addr_of! and addr_of_mut! macros let you safely work with potentially unaligned or unsafe memory locations without creating invalid references.
✅ The Solution: addr_of! and addr_of_mut!
Rust provides two macros specifically for these cases:
addr_of!→ create a raw pointer*const Taddr_of_mut!→ create a raw pointer*mut T
The critical point: ✅ These macros compute the address without creating a reference, that means you can safely obtain the pointer to an unaligned field.