I have a following struct:
pub struct Foo {
v: Vec<T>, // `T` is a struct that does not implement `Copy` trait
index: u32,
}
inside this struct's implementation I have following method:
fn foo(&mut self) -> Box<dyn E> {
let t = self.peek();
Box::new(Bar::new(t).unwrap()) // constructor of `Bar` takes `&T` and returns `Option<Bar>`
}
// returns `T` at current `index`
// since `T` does not implement `Copy` I have to return reference
fn peek(&self) -> &T{
&self.v[self.index as usize]
}
E
is some trait that returned value should implement, Bar
is a struct that takes reference to T
. Again, since T
does not implement Copy
, I have to pass it as a reference, which also forces me to impose lifetime requirements on struct Bar
:
// if my understanding is correct, this means `Bar` lives as long as `field` does
pub struct Bar<'a> {
field: &'a T,
}
However, when I try to compile the code I get following error message:
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src\parser.rs:78:29
|
64 | fn foo(&mut self) -> Box<dyn Expr> {
| --------- this data with an anonymous lifetime `'_`...
...
78 | let t = self.peek();
| ---- ^^^^
| |
| ...is captured here...
79 | Box::new(Binary::new(t).unwrap())
| ---------------------------------------------------- ...and is required to live as long as `'static` here
|
help: to declare that the trait object captures data from argument `self`, you can add an explicit `'_` lifetime bound
|
64 | fn foo(&mut self) -> Box<dyn Expr + '_> {
| ^^^^
Why is the error occurring here? Why is the compiler asking for the 'static
lifetime?