我有一个特性,其中包含一个接受迭代器引用的函数:
#[derive(Clone)]
struct Dog {
name: &'static str,
}
trait DogListAction<'a, I>
where
I: Iterator<Item = &'a Dog>,
{
fn on_dog_list(&mut self, dog_list: I);
}
struct DogListActionExample {}
impl<'a, I> DogListAction<'a, I> for DogListActionExample
where
I: Iterator<Item = &'a Dog>,
{
fn on_dog_list(&mut self, dog_list: I) {
for dog in dog_list {
println!("{}", dog.name);
}
}
}
fn main() {
let dogs = vec![Dog { name: "Pluto" }, Dog { name: "Lilly" }];
let mut action_example = DogListActionExample {};
let mut dog_list_actions: Vec<Box<DogListAction<_>>> = vec![Box::new(action_example)];
loop {
let dog_clone = dogs.clone();
for dog_list_action in &mut dog_list_actions {
dog_list_action.on_dog_list(dog_clone.iter());
}
}
}
它不需要引用元素,因此无需在函数调用后保留。 由于我对生命期的理解有限,我还不知道如何表达这一点。 调用此函数会导致编译错误:
error[E0597]: `dog_clone` does not live long enough
--> src/main.rs:33:41
|
33 | dog_list_action.on_dog_list(dog_clone.iter());
| ^^^^^^^^^ borrowed value does not live long enough
34 | }
35 | }
| - `dog_clone` dropped here while still borrowed
36 | }
| - borrowed value needs to live until here
我想借用检查器认为 dog_clone
中的数据可能在函数结束后被引用,但实际上并非如此。
dog_clone
元素的引用保存到长寿命周期的dog_list_actions
元素中。 - red75primedog_clone.iter()
替换为dogs.iter()
,代码就可以编译。你需要让函数on_dog_list()
的签名表达你不想保存迭代器产生的引用的意图。 - red75prime