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.

RustData Integrity

Code

rustsnippet
39 lines
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

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`.