Trouble with lifetimes


#1

I have the following struct in one of the crates that I’m using.

pub struct Set<'a, 'b: 'a, 'c: 'a + 'b> {
    sockets: ManagedSlice<'a, Option<Item<'b, 'c>>>
}

impl<'a, 'b: 'a, 'c: 'a + 'b> Set<'a, 'b, 'c> {
    
    pub fn new<SocketsT>(sockets: SocketsT) -> Set<'a, 'b, 'c>
            where SocketsT: Into<ManagedSlice<'a, Option<Item<'b, 'c>>>> {
        let sockets = sockets.into();
        Set {
            sockets: sockets
        }
    }
}

I need to have struct Set as one of the fields in another struct. For example,

pub struct foo {
sockets:Set,
}

impl foo {
        pub fn init(&mut self){
            self.sockets = Set::new(vec![]);
        }
}

But this results in the following error.

   |
21 |     sockets:Set,
   |             ^^^^^^^^^ expected 3 lifetime parameters

I read about advance lifetimes in rust, but could not figure out how to work this out. How to correctly set the lifetimes here?


#2

You would need to declare the lifetimes in the foo struct declaration and then use them in the sockets field declaration. Unless you intend to/can use 'static for all 3 lifetime parameters.


#3

I’m unclear on how to declare life times in the foo struct (not the syntax). I tried different ways of declaring them but they did not work. I would like to know the thinking pattern on how to do it.


#4

If they’re all generic, then it’ll be essentially a repeat of what’s in Set itself:

struct foo<'a, 'b: 'a, 'c: 'a + 'b> {
   sockets: Set<'a, 'b, 'c>,
}

What did you try that didn’t work?


#5

I managed to get it to work using 'static for all lifetime parameters. The above code resulted in a compiler error where it complained that it could not infer lifetime of c.