struct Data {
val: String,
}
struct Item<'a> {
data: &'a Data,
}
struct Container<'a> {
src: Vec<Data>,
items: Vec<Item<'a>>,
}
impl<'a> Container<'a> {
fn new() -> Container<'a> {
Container {
src: vec![Data { val: String::from("test") }],
items: Vec::new(),
}
}
fn build(&mut self) {
let first = &self.src[0];
self.items.push(Item { data: first });
self.items.push(Item { data: first });
}
}
first
cannot outlive anonymous lifetime '_
defined on method body. That makes sense, because elements of self.src
may be deleted so their minimum lifetime is '_
.
But, I know I will never delete any element from self.src
, so first
lives as long as 'a'
. Rust compiler doesn't know that, so it complains about conflicting lifetime '_
and 'a
.
How to tell Rust compiler that first
lives as long as 'a
? Or, is there a better way to solve the problem?