I have a problem about the lifetimes of the following code. I was wondering if someone could give me a hint.
struct Listener<'a> {
stream: &'a mut Stream<'a>
}
impl<'a> Listener<'a> {
fn new(stream: &'a mut Stream<'a>) -> Self {
Listener {
stream
}
}
}
struct Stream<'b> {
listener: Option<Listener<'b>>
}
impl<'b> Stream<'b> {
fn new() -> Self {
Stream {
listener: None
}
}
}
impl<'b> Drop for Stream<'b> {
fn drop(&mut self) {}
}
fn main() {
let mut stm = Stream::new();
let lis = Listener::new(&mut stm);
}
The code cannot be compiled since there will be an error:
error[E0597]: `stm` does not live long enough
--> src/main.rs:31:34
|
31 | let lis = Listener::new(&mut stm);
| ^^^ borrowed value does not live long enough
32 | }
| - `stm` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
My understanding is that the stm
will be dropped after lis
is dropped. That means stm
will live longer than lis
. If it's right, then I am confused about the error I got.
On the other hand, if I comment the implementation for Drop
trait, then the code can be compiled successfully.
struct Listener<'a> {
stream: &'a mut Stream<'a>
}
impl<'a> Listener<'a> {
fn new(stream: &'a mut Stream<'a>) -> Self {
Listener {
stream
}
}
}
struct Stream<'b> {
listener: Option<Listener<'b>>
}
impl<'b> Stream<'b> {
fn new() -> Self {
Stream {
listener: None
}
}
}
// impl<'b> Drop for Stream<'b> {
// fn drop(&mut self) {}
// }
fn main() {
let mut stm = Stream::new();
let lis = Listener::new(&mut stm);
}
I don't why the drop
can affect the lifetime checking here. If someone know how to fix the above problem properly, please let me know. Thanks!