Why does this code `lifetime` conflicting requirements?

Rust playgroud

use std::marker::PhantomData;

mod tower {
    // This trait from a third-party library.
    pub trait Service {
        type Response;
        fn call(&mut self) -> Self::Response;
    }
}

struct Send<'a, T> {
    inner: &'a T,
}

struct Sender;

impl Sender {
    fn send(&self) -> Send<'_, Self> {
        Send { inner: self }
    }
}

struct Client<'a> {
    sender: Sender,
    _marker: PhantomData<&'a ()>,
}

struct Call<'a, T> {
    inner: Send<'a, T>,
}

impl<'a> tower::Service for Client<'a> {
    type Response = Call<'a, Sender>;

    fn call(&mut self) -> Self::Response {
        Call {
            inner: self.sender.send(),
        }
    }
}

Compiler output:

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/main.rs:37:32
   |
37 |             inner: self.sender.send(),
   |                                ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 35:5...
  --> src/main.rs:35:5
   |
35 | /     fn call(&mut self) -> Self::Response {
36 | |         Call {
37 | |             inner: self.sender.send(),
38 | |         }
39 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:37:20
   |
37 |             inner: self.sender.send(),
   |                    ^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 32:6...
  --> src/main.rs:32:6
   |
32 | impl<'a> tower::Service for Client<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/main.rs:35:42
   |
35 |       fn call(&mut self) -> Self::Response {
   |  __________________________________________^
36 | |         Call {
37 | |             inner: self.sender.send(),
38 | |         }
39 | |     }
   | |_____^
   = note: expected  `tower::Service`
              found  `tower::Service`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0495`.
error: could not compile `demo`.

To learn more, run the command again with --verbose.

I think this lifetime can be deduced.

What should I do? Thank you.

The Service trait does not allow the response to contain references into self.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.