Standalone types to represent variance

โš“ Rust    ๐Ÿ“… 2025-07-12    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 2      

surdeus

Currently if you want to express your typeโ€™s variance with respect to generic parameter, perhaps with a generic lifetime parameter 'a, you have to include a PhantomData field with something like &'a T, fn(&'a T), or fn(T) -> T. These are pretty โ€œmagicalโ€ and require a fair amount of reasoning to determine why they're correct.

Why doesn't Rust just have (say) PhantomCovariant<T>, PhantomContravariant<T>, and PhantomInvariant<T>, so that you could replace e.g. PhantomData<fn(T) -> T> with the much clearer PhantomInvariant<T>? (These would simply be defined in terms of PhantomData.) This would be more explicit, less magical.

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ rust_feed