I am writing a toy program for learning networking and server, and in a simple struct I have lifetimes issues. The error "self
has an anonymous lifetime '_
but it needs to satisfy a 'static
lifetime requirement" popped when trying to compile. While I understand that I need to add 'static to self I don't understand why. I isolated the problem it's from the lock() call on the mutex. Do I need the Pin ?
pub type PtrMtx<T> = Arc<Mutex<T>>;
pub struct Server {
sessions: PtrMtx<Vec<Session>>,
connected: PtrMtx<HashMap<Uuid, Option<SessionId>>>,
}
impl Server {
pub fn new() -> Self {
Server {
sessions: ptr_mtx(vec![]),
connected: ptr_mtx(HashMap::new()),
}
}
pub async fn handle(&self, mut stream: TcpStream) -> Result<(), BoxError> {
let length_delimited =
FramedRead::new(stream, LengthDelimitedCodec::new());
let mut deserialized =
tokio_serde::SymmetricallyFramed::new(length_delimited, SymmetricalBincode::<Message>::default());
if let Some(message) = deserialized.try_next().await? {
// first message from a client
match message.action {
Input::CreateSession(password) => {
let id = Uuid::new_v4();
self.sessions.lock()?.push( // if commented it compiles
Session::new(id, format!("Session of {}", id), password)
)
}
_ => {}
}
}
Ok(())
}
}
And the error :
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/server/mod.rs:99:25
|
99 | pub async fn handle(&self, mut stream: TcpStream) -> Result<(), BoxError> {
| _________________________^^^^^_________________________________________________-
| | |
| | this data with an anonymous lifetime `'_`...
| | ...is captured here...
100 | | let length_delimited =
101 | | FramedRead::new(stream, LengthDelimitedCodec::new());
102 | | let mut deserialized =
... |
118 | | Ok(())
119 | | }
| |_____- ...and is required to live as long as `'static` here