Lifetimes on trait or structure declarations

pub struct SessionManager<'cxn, 'driver: 'cxn, 'server: 'driver> where Self: 'driver {
    
}

impl<'cxn, 'driver: 'cxn, 'server: 'driver> SessionManager<'cxn, 'driver, 'server> where Self: 'server {
    fn test_fn(&self) where Self: 'cxn {

    }
}

As you can see above, there are three different where clauses. I am interested in knowing what each lifetime means in reference to structures, impls, and functions. Also, when returning an object with multiple lifetimes, does the order matter (e.g., does SessionManager<'cxn, 'driver, 'server> == SessionManager<'server, 'driver, 'cxn>?)

When you have a lifetime as bound it always mean "must lasts at least as long as this lifetime". For a struct it means it can't contain reference or other type that last less than the specified lifetime.

Yes! You can think of lifetimes as regular generics.

struct Generic<A, B>((A, B));

If you make Generic<u32, usize> it's not the same type as Generic<usize, u32>.

You can read about it in the reference or rust-by-example, and when you want to quickly check there is this website.

1 Like

Therefore, this would not compile then?

pub struct SessionManager<'cxn, 'driver: 'cxn, 'server: 'driver> where Self: 'driver {
    field: &'cxn ()
}

(omitted the addition of other lifetime variables in fields; just wanted the idea across that having a field with a 'cxn lifetime would not suffice because Self: 'driver and 'driver: 'cxn

When I say

there is an "or equal" omitted so

isn't an issue in itself.

Also Self: driver doesn't really do anything since a type can't hold a reference shorter than itself. It would mean the struct is holding an invalid reference at some point, the compiler won't let you. But the compiler is also very tolerant on lifetimes as long as it doesn't result in invalid state.