Using PhantomData to "use" a lifetime in a trait bound


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.


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.