repr(transparent) Newtype Layout

Guarantee a one-field wrapper has the identical memory layout as its inner type with #[repr(transparent)], so transmutes and FFI stay sound.

RustData Integrity

Code

rustsnippet
29 lines
use std::mem::{size_of, align_of};

// repr(transparent):单字段包装类型保证与内部类型布局完全一致
// (否则 newtype 的大小虽相同,对齐与 ABI 不承诺一致)
#[repr(transparent)]
#[derive(Debug)]
struct Millis(u64);

// 不加 repr 时只是普通 newtype:大小通常一样,但布局不构成保证
#[derive(Debug)]
struct Plain(u64);

fn main() {
    println!("u64 size {} align {}", size_of::<u64>(), align_of::<u64>());
    println!("Millis size {} align {}", size_of::<Millis>(), align_of::<Millis>());
    println!("Plain size {} align {}", size_of::<Plain>(), align_of::<Plain>());

    // 布局一致意味着 FFI 边界上可按 u64 传 Millis:
    // repr(transparent) 是 C ABI 承诺的前提
    let m = Millis(1500);
    let raw = unsafe {
        // 两个类型 size/align 相同且 Millis 是 repr(transparent):合法
        std::mem::transmute::<Millis, u64>(m)
    };
    println!("transmuted back: {raw}");

    // 多字段类型不能用 repr(transparent):编译器直接拒绝
    // #[repr(transparent)] struct Two(u8, u8); // error
}

How it works

repr(transparent) Newtype Layout reduces to the function main.

Caveats

  • std::mem is the only import the file needs; size_of and align_of perform every measurement the demo makes.

Using it

Signature: fn main()

The file’s steps show up in the output as u64 size, Millis size, Plain size.

Key statements

let raw = unsafe {
    // 两个类型 size/align 相同且 Millis 是 repr(transparent):合法
    std::mem::transmute::<Millis, u64>(m)
};

Interactive Tools for This Topic

FAQ

What does repr(transparent) Newtype Layout print when run?
Execute the whole file; each printed line is prefixed with a label like `u64 size`, `Millis size`, `Plain size`.