Type Sizes With size_of And align_of
Print std::mem sizes and alignments for primitives and a repr(C) struct to reason about padding, cache lines, and buffer layout.
Code
use std::mem::{align_of, size_of, size_of_val};
#[repr(C)]
struct Packet {
kind: u8,
sequence: u16,
length: u32,
}
#[repr(C)]
struct Tail {
kind: u8,
sequence: u16,
length: u32,
trailer: u8,
}
fn main() {
println!("u8: size {} align {}", size_of::<u8>(), align_of::<u8>());
println!("u16: size {} align {}", size_of::<u16>(), align_of::<u16>());
println!("u32: size {} align {}", size_of::<u32>(), align_of::<u32>());
println!("u64: size {} align {}", size_of::<u64>(), align_of::<u64>());
// Type sizes and alignment: padding follows the alignment rules
println!(
"Packet: size {} align {}",
size_of::<Packet>(),
align_of::<Packet>()
);
println!(
"Tail: size {} align {}",
size_of::<Tail>(),
align_of::<Tail>()
);
let buffer = [0u8; 16];
println!("array bytes: {}", size_of_val(&buffer));
println!("element bytes: {}", size_of::<u8>());
}How the snippet works
Type Sizes With size_of And align_of keeps everything in the function main.
Using it
The run emits 8 labeled sections — u8: size, u16: size, u32: size, u64: size, Packet: size, Tail: size, array bytes:, element bytes: — one per step.
Key statements
let buffer = [0u8; 16];
align_of::<Packet>()
);
align_of::<Tail>()
);
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.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.
FAQ
- What does Type Sizes With size_of And align_of print when run?
- Execute the whole file; each printed line is prefixed with a label like `u8: size`, `u16: size`, `u32: size`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.