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.
Code
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
CSS Flexbox PlaygroundInteractively test CSS flexbox container and item properties with a live preview. Adjust justify-content, align-items, flex-direction, and flex-grow to see layout changes.CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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 @`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.