Variance inference across generic type arguments

โš“ rust    ๐Ÿ“… 2025-04-25    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 4      

surdeus

Hello,

I'm a bit embarrassed to admit that I've been working in Rust for 5 years now and I still haven't managed to get the variance inference behavior clear in my head.

Specifically in this code below, I'm not sure what I have to do, to make it clear that the lifetime in the use_container_generic function can be shortened. It has no problem figuring that out when the parameter type is not generic. (in use_container_specific)

pub trait RefTrait<'a> { }

impl<'a> RefTrait<'a> for &'a usize {}

pub struct Container<'contents, 'src> {
    contents: Vec<Box<dyn RefTrait<'src> + 'contents>>
}

impl<'contents, 'src> Container<'contents, 'src> {
    pub fn new<Cont1, Cont2>(primary: Cont1, secondary: Cont2) -> Self
        where
        Cont1: RefTrait<'src> + 'contents,
        Cont2: RefTrait<'src> + 'contents,
    {
        let mut contents = Vec::new();
        contents.push(Box::new(primary) as Box<dyn RefTrait<'src> + 'contents>);
        contents.push(Box::new(secondary) as Box<dyn RefTrait<'src> + 'contents>);
        Self{contents}
    }
}

fn use_container_generic<'long, RZ>(long_lived: RZ)
    where RZ: RefTrait<'long>
{
    let short_lived: usize = 2;
    let _ = Container::new(long_lived, &short_lived);
}

fn use_container_specific<'long>(long_lived: &'long usize)
{
    let short_lived: usize = 2;
    let _ = Container::new(long_lived, &short_lived);
}

fn main() {
    let long_lived: usize = 1;
    use_container_generic(&long_lived);
    use_container_specific(&long_lived);
}

I saw a people discussing PhantomFn which seems like it might be what I need (e.g. here: rfcs/text/0738-variance.md at master ยท rust-lang/rfcs ยท GitHub), but it doesn't appear to be part of contemporary Rust.

Thanks for any thoughts.

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ rust_feed