Replacing Rc by reference with lifetime specifier


#1

I have got the following working code:

struct Server {
    adapter: Rc<Adapter>,
}

impl Server {
    fn new(adapter: Rc<Adapter>) -> Server {
        Server { adapter }
    }
}

Now I am trying to reorganize the code, so the struct holds &Adapter instead of Rc<Adapter>. Not a big deal for the app to leave it as Rc, but I want to learn on this simple example. Once I tried to do this, I got:

29 |     adapter: &Adapter,                    
   |              ^ expected lifetime parameter

I have tried to specify it on the variable type, but it seems I need to specify for the new function as well, and I got lost. How should I fix this error reported by the compiler?


#2
struct Server<'a> {
   adapter: &'a Adapter,
}

impl<'a> Server<'a> {
     fn new(adapter: &'a Adapter) -> Self {
          Self { adapter }
     }
}

Keep in mind that hyper (which is where I think you’re at here) may ultimately require giving it a Service that’s 'static. So unless you can get a &'static Adapter (doubtful, I’m guessing), it won’t work anyway.


#3

All my problems with lifetimes started once I needed to pass &Core::handle to the Adapter as per the other question I asked. I need to save the handle to Adapter struct and this enforced lifetimes for the Adapter and the Server holding the adapter, etc. now I fighting though the chain of errors. Will keep trying :frowning:


#4

Handle is cloneable, so you should be able to pass clones around your various components that need access to it.


#5

Nice. Now it works.