https://github.com/djmitche/rubbish/blob/e98d654fc6cc1bdf8aae233d55e2e7a35dc7f85e/src/fs/lazy.rs#L36:46
Rust seems not to recognize the trait bound on line 14 as "using" 'f, C
, so I added a PhantomData to use those. However, when constructing the type the recommended _phantom: &PhantomData
results in a lifetime mismatch, because PhantomData
in that case has a lifetime bounded by the function body, which is smaller than 'f
. So I added the function on line 36 which "upgrades" the lifetime to 'f
as required.
This seems pretty gross. Is there a better way?
Instead of _phantom: &'f PhantomData<C>
, use _phantom: PhantomData<&'f C>
to construct it easily using only safe code.
2 Likes
If it's unclear why that is, it's because the compiler needs to figure out the variance of your struct; to do that, it needs to know how the types and/or lifetimes are used internally. A constraint just restricts what types can be used for T
, in your example, but doesn't actually make use of C or 'f internally.