我试图在使用回调的一段代码中实现CLONE_INTO_BOX模式,但我遇到了一个难以理解的错误.
基本上,我是在克隆lambda的参数,但borrow 判断器仍然抱怨我泄露了对所述参数的引用.
我的问题是:这是borrow 判断器过于保守的情况(如果是这样的话,我如何才能以一种与borrow 判断器很好地配合的方式重写这篇文章),或者是我在这里遗漏了什么,尽管有克隆,但引用确实被泄露了吗?
代码:
pub trait CloneIntoBox{
fn clone_into_box<'a>(&self) -> Box<dyn CloneIntoBox + 'a>;
}
impl<'a> Clone for Box<dyn CloneIntoBox + 'a> {
fn clone(&self) -> Self {
self.as_ref().clone_into_box()
}
}
#[derive(Clone)]
pub struct StructWithBox<'a> {
pub my_box: Box<dyn CloneIntoBox + 'a>,
}
#[derive(Clone)]
struct StructThatCanBeClonedIntoBox {
pub data: u32,
}
impl CloneIntoBox for StructThatCanBeClonedIntoBox {
fn clone_into_box<'a>(&self) -> Box<dyn CloneIntoBox + 'a> {
Box::new(self.clone())
}
}
pub type WalkCallback<'a> = dyn FnMut(&StructWithBox) + 'a;
pub fn walk(data: Vec<u32>, cb: &mut WalkCallback) {
for d in data{
let instance = StructWithBox{my_box: Box::new(StructThatCanBeClonedIntoBox{data:d})};
cb(&instance);
}
}
fn main() {
let data = vec![1, 2];
let mut result = vec![];
walk(data, &mut|param| result.push((*param).clone()));
}
提供:
error[E0521]: borrowed data escapes outside of closure
--> src/main.rs:39:28
|
38 | let mut result = vec![];
| ---------- `result` declared here, outside of the closure body
39 | walk(data, &mut|param| result.push((*param).clone()));
| ----- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `param` escapes the closure body here
| |
| `param` is a reference that is only valid in the closure body