I'm still having trouble getting lifetimes correct for functions building vectors of references.
The following code builds up a recursive data structure for a family tree using Person node elements.
The problem I'm having is in the method Person::collect() where I wish to build and return a Vec<&Person> collection holding the Person objects where the passed in closure returns true.
At the end of main() this function is used with the hopes of obtaining a Vector holding references to all Person for people in their 50's.
Here's the code and following that the error I get compiling it.
struct Person<'a> {
name: &'a str,
age: i32,
children: Vec<Person<'a>>,
}
impl<'a> Person<'a> {
fn new(name: &'a str, age: i32) -> Person<'a> {
Person {
name: name,
age,
children: Vec::new(),
}
}
fn add(&mut self, name: &'a str, age: i32) -> &mut Person<'a> {
self.children.push(
Self::new(name, age)
);
self
}
fn show(&self) {
self.show_w_tab(0);
}
fn show_w_tab(&self, tab: usize) {
println!("{:>1$}, {age} yrs old",
self.name, tab + self.name.len(), age=self.age);
}
fn show_r(&self, tab: usize) {
self.show_w_tab(tab);
for c in self.children.iter() {
c.show_r(tab + 4);
}
}
fn show_family_tree(&self) {
self.show_r(0)
}
fn collect_r<'b>(&'a self, result: &'b mut Vec<&'a Person<'a>>,
filter: fn(&'a Person) -> bool) {
if filter(self) {
result.push(self);
}
for c in self.children.iter() {
c.collect_r(result, filter);
}
}
fn collect(&self, filter: fn(&Person) -> bool) -> Vec<&Self> {
let mut result: Vec<&Person>;
self.collect_r(&mut result, filter);
result
}
}
fn main() {
let mut person1 = Person::new("Ruth", 120);
person1
.add("Pat", 91)
.add("John", 89);
person1.children[0]
.add("Jim", 65)
.add("Chuck", 65);
person1.children[1]
.add("Stan", 57)
.add("Anne", 55);
person1.children[1].children[1]
.add("Helena", 21)
.add("Peter", 19);
person1.show_family_tree();
let fifties = person1.collect(|p| p.age >= 50 && p.age < 60);
println!("fifties...");
for p in fifties.iter() {
p.show();
}
}
Here are the errors, and when I try to fix them I just get more errors that confuse the matter even more.
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/main.rs:49:14
|
49 | self.collect_r(&mut result, filter);
| ^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime defined on the method body at 47:16...
--> src/main.rs:47:16
|
47 | fn collect(&self, filter: fn(&Person) -> bool) -> Vec<&Self> {
| ^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:49:9
|
49 | self.collect_r(&mut result, filter);
| ^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 8:6...
--> src/main.rs:8:6
|
8 | impl<'a> Person<'a> {
| ^^
note: ...so that the expression is assignable
--> src/main.rs:50:9
|
50 | result
| ^^^^^^
= note: expected `Vec<&Person<'a>>`
found `Vec<&Person<'_>>`
error: aborting due to previous error