Field Offsets With offset_of

Pin down portable wire layouts with repr(C) and offset_of!: read each field byte offset and the total struct size without hand-computed padding.

RustData Integrity

Code

rustsnippet
19 lines
use std::mem::{offset_of, size_of};

// repr(C) 固定字段声明顺序与对齐规则:每个 field 的字节偏移量才可移植。
// 没有固定布局保证时,offset_of 给出的 field offsets 不应进线上协议
#[repr(C)]
struct Header {
    magic: u8,
    version: u8,
    length: u16,
    checksum: u32,
}

fn main() {
    println!("magic    @ {}", offset_of!(Header, magic));
    println!("version  @ {}", offset_of!(Header, version));
    println!("length   @ {}", offset_of!(Header, length));
    println!("checksum @ {}", offset_of!(Header, checksum));
    println!("size     = {}", size_of::<Header>());
}

How it works

The moving parts are the function main.

Points of care

  • Runs on the standard library alone; nothing to install.

Working with it

The headline signature is fn main()

Output lines are prefixed (magic @, version @, length @), so the effect of each step is easy to spot.

Interactive Tools for This Topic

FAQ

What does Field Offsets With offset_of print when run?
Run it as a complete program — the output lines carry labels such as `magic @`, `version @`, `length @`.