Alignment and initialization
Quick answer
A typed memory access requires more than enough bytes: the address must meet alignment rules, and the bytes must represent a valid initialized value of the type.
Decode bytes without invalid references
Alignment is an address requirement for a type. Size equality does not imply interchangeable representations; for example, bool admits only its valid bit patterns. Use from_le_bytes or from_be_bytes for byte-oriented data. read_unaligned relaxes the alignment requirement only, not validity, provenance or readable bounds.
fn main() { let b = [0x34, 0x12]; println!("{}", u16::from_le_bytes(b)); }Expected stdout (not executed):
4660The byte order is explicit and no pointer cast is needed.
fn main() { let b = [0u8, 0x34, 0x12]; let p = b[1..].as_ptr().cast::<u16>(); // SAFETY: two initialized readable bytes remain; all u16 patterns valid; // no conflicting access, and read_unaligned accepts any alignment. let native = unsafe { p.read_unaligned() }; println!("{}", u16::from_le(native));}Expected stdout (not executed):
4660No u16 reference is created, and endianness is normalized. Prefer the first approach.
Common mistake
Do not create a reference to an unaligned field before calling read_unaligned.
Try it yourself
Decode a two-byte big-endian field with a safe conversion.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Alignment and initialization — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A two-byte field is at an unaligned byte offset. Which approach avoids forming an invalid typed reference?
Alignment and initialization — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let b = [0x34, 0x12]; println!("{}", u16::from_le_bytes(b)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Alignment and initialization — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let b = [0u8, 0x34, 0x12]; let p = b[1..].as_ptr().cast::<u16>(); // SAFETY: two initialized readable bytes remain; all u16 patterns valid; // no conflicting access, and read_unaligned accepts any alignment. let native = unsafe { p.read_unaligned() }; println!("{}", u16::from_le(native)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.