PhantomData Encodes Units Zero Cost

PhantomData carries a unit type at zero runtime cost, so Meters and Feet are distinct compile-time types and mixing them simply fails to compile.

RustData Integrity

Code

rustsnippet
34 lines
use std::marker::PhantomData;

struct Meters;
struct Feet;

struct Length<Unit> {
    raw: f64,
    // 单位只活在类型层面:PhantomData 零大小,不占任何运行时内存
    _unit: PhantomData<Unit>,
}

impl<Unit> Length<Unit> {
    fn new(raw: f64) -> Self {
        Self { raw, _unit: PhantomData }
    }
}

// 只有 Meters 单位才提供换算:Feet 没有 to_feet,混用直接编译失败
impl Length<Meters> {
    fn to_feet(&self) -> Length<Feet> {
        Length::new(self.raw * 3.28084)
    }
}

fn main() {
    let runway = Length::<Meters>::new(2600.0);
    let feet = runway.to_feet();
    println!("runway: {:.0} m = {:.0} ft", runway.raw, feet.raw);

    // 编译期防混用:取消注释无法编译(类型不同且 Feet 无该转换)
    // let wrong: Length<Meters> = feet;

    println!("marker size: {}", std::mem::size_of::<PhantomData<Meters>>());
}

How the snippet works

PhantomData Encodes Units Zero Cost comes down to the functions new, to_feet and main.

Applying it

Entry signature: fn new(raw: f64) -> Self

Output lines are prefixed (runway:, marker size:), making each step’s effect easy to spot.

Running the file executes main, which drives new and to_feet in order.

Statements that matter

fn to_feet(&self) -> Length<Feet> {
    Length::new(self.raw * 3.28084)
}
fn new(raw: f64) -> Self {
    Self { raw, _unit: PhantomData }
}

Interactive Tools for This Topic

FAQ

What does PhantomData Encodes Units Zero Cost print when run?
The script runs standalone; its 2 labeled outputs include `runway:`, `marker size:`.