expression

Read a packed field without creating a reference

Packed layout reduces alignment constraints. A field may be stored at an address unsuitable for an ordinary reference. Copy the field directly in safe code when possible; a raw pointer and read_unaligned demonstrate the low-level alternative. Expected stdout (not executed): 1 300 Common mistake: Borrowing a packed field via &packet.count, including implicit borrows in formatting.

Formal Syntax & Structure

rust syntaxrust
#[repr(C, packed)] ; &raw const field

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    #[repr(C, packed)]    struct Sample { tag: u8, count: u16 }    let packet = Sample { tag: 1, count: 300 };    let ptr = &raw const packet.count;    // SAFETY: count is a live initialized Copy u16 in packet, readable for its full size;    // read_unaligned does not require the address to meet u16 alignment.    let count = unsafe { std::ptr::read_unaligned(ptr) };    println!("{} {count}", packet.tag);}
Rust Reference