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.
Code
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
bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.
FAQ
- What does PhantomData Encodes Units Zero Cost print when run?
- The script runs standalone; its 2 labeled outputs include `runway:`, `marker size:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.