Lifetime does not live long enough

trait TraitA<'a, 'b>
where
    'a: 'b,
{
    fn needs_ref(&'a self, val: &'b u32) -> u32;
    fn foo(&'a self) -> u32 {
        let i: u32 = 0xdeadbeef;
        self.needs_ref(&i)
    }
}

Hello there, Rust newbie here. I'm trying to get straight about this lifetime constraint that requires 'a outlives 'b it's clear that i is a temporary value and simply lives shorter than 'a. But this code simply cannot compile. It says i dropped while still borrowed. Why this fails?

'b is "solidified" at trait definition level and i has some other lifetime 'c, The compiler sees 'c can't outlive 'b, so it fails.

Put it in another way, needs_ref is not generic over 'b.

No, this is not true; the trait that contains needs_ref is generic over 'b, so needs_ref can't be any more concrete than that; it must be (transitively) generic over 'b.

However, luckily, this has nothing to do with the issue at hand!

The generic lifetime parameters (and in general, all generic parameters of a function) are chosen by the caller of the function. They can be arbitrarily long, so if 'b is chosen to be e.g. 'static, that would imply that you just took a &'static reference to a local variable! This is clearly nonsensical.

1 Like

Sry for my late gratitude. This explanation makes tons of sense. Huge Thanks!

You could do something like this (but if you're doing more than exploring, I can't say if it would help and this whole topic is an XY problem).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.