std-method

Read a packed field without creating an unaligned reference

read_unaligned removes the ordinary alignment requirement for a read, not the requirements for readable storage and an initialized valid value. Use raw borrow syntax for a packed field so an invalid intermediate reference is not formed. Prefer ordinary safe access when possible. Expected stdout (not executed): 1:25 Common mistake: Creating &packet.count first and then casting it to a raw pointer.

Formal Syntax & Structure

rust syntaxrust
p.read_unaligned()

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    #[repr(C, packed)]    struct Packet { kind: u8, count: u32 }    let packet = Packet { kind: 1, count: 25 };    let p = &raw const packet.count;    // SAFETY: count is a live initialized u32 field; read_unaligned handles alignment.    let count = unsafe { p.read_unaligned() };    println!("{}:{count}", packet.kind);}
Rust Reference