Any way to guarantee reference to ZST in PhantomData is zero-cost

⚓ Rust    📅 2025-07-24    👤 surdeus    👁️ 1      

surdeus

I have two types that look like this:

pub type Foo<'a> = PhantomData<fn(&'a ()) -> &'a ()>;
pub struct Bar<'a>(PhantomData<&'a Foo<'a>>);

How can I construct a Bar and with the same lifetime as a Foo and be guaranteed constructing Bar has zero overhead?

One way to do it is like this:

impl<'a> Bar<'a> {
    pub fn new(_: &'a Foo<'a>) -> Self {
        Bar(PhantomData)
    }
}
let foo: Foo = PhantomData;
let bar = Bar::new(&foo);

But this is no longer guaranteed to be zero-cost, as I create a reference to a ZST which is not guaranteed to be zero sized or optimized away. And changing the constructor to take in a Foo<'a> without a reference changes the behavior of my program. I feel like there should be a way to do this without actually creating the reference, or am I asking for too much and is this not possible?

7 posts - 3 participants

Read full topic

🏷️ Rust_feed