Trying to understand rust and hitting into a some or the other wall each time. Hoping, the frequent posting is not considered spamming.
Again some code that does not do anything meaningful. Create vector of Person
struct and runs a fold on it.
#[derive(Debug)]
pub struct Person {
first: String,
last: String,
}
pub fn main() {
let person_vec = vec![
Person {
first: String::from("James"),
last: String::from("Croft")
},
Person {
first: String::from("Monica"),
last: String::from("Flint")
}
];
person_vec
.iter()
.fold(Vec::new(), |mut acc, per| {
if per.first == "James" {
acc.push(per);
return acc
}
let roma = Person {
first: String::from("Roma"),
last: per.last.clone()
};
acc.push(&roma);
acc
});
}
It fails with -
Compiling playground v0.0.1 (/playground)
error[E0597]: `roma` does not live long enough
--> src/main.rs:31:22
|
31 | acc.push(&roma);
| ^^^^^ borrowed value does not live long enough
32 | acc
33 | });
| - `roma` dropped here while still borrowed
error: aborting due to previous error
The error is pretty clear that roma
will go out scope after the call to the anonymous function is done and the reference push
(ed) to the acc
will be invalid.
Question: How to work around this situation? Implement a copy trait? What if the struct is large enough that copy(ing) is expensive?