我有一个结构包装了
Box<dyn Any>
构造函数的 Vec,我断言它是克隆的。
我有一个特征
Ctor
,它采用克隆逻辑并产生另一个Box<dyn Ctor>
。如果我不实现特征或不调用克隆函数,它编译得很好。
但是如果我同时执行这两项操作,我会收到一条奇怪的消息,声称数据超出了其生命周期范围,即使我断言该值为
'static
.
(代码比上面的描述更容易阅读,但是如果您的帖子中没有足够的英文文本,stackoverflow 会抱怨,如果您在 stackoverflow 帖子中放置 lorem ipsum,吹毛求疵的人会抱怨)
取消注释下面的任何一个块都可以正常编译,但同时取消注释两个块会导致错误:
use std::any::Any;
// pub struct SVConstructor {
// ctors: Vec<Box<dyn Ctor + 'static>>,
// }
// impl Clone for SVConstructor {
// fn clone(&self) -> Self {
// let Self { ctors } = self;
// let mut new_ctors: Vec<Box<dyn Ctor + 'static>> = Vec::new();
// for ctor in ctors {
// let value: Box<dyn Ctor + 'static> = ctor.clone_box();
// drop(ctor);
// new_ctors.push(value);
// }
// Self { ctors: new_ctors }
// }
// }
pub trait Ctor: Fn() -> Box<dyn Any + Send + Sync + 'static> + Send + Sync {
fn clone_box(&self) -> Box<dyn Ctor + 'static>;
}
// impl<T: Fn() -> Box<dyn Any + Send + Sync + 'static> + Send + Sync + Clone + 'static> Ctor for T {
// fn clone_box(&self) -> Box<dyn Ctor + 'static> {
// Box::new(self.clone())
// }
// }
当我取消注释我得到的所有内容时:
error[E0521]: borrowed data escapes outside of associated function --> src/lib.rs:12:50 | 8 | fn clone(&self) -> Self { | ----- | | | `self` is a reference that is only valid in the associated function body | let's call the lifetime of this reference `'1` ... 12 | let value: Box<dyn Ctor + 'static> = ctor.clone_box(); | ^^^^^^^^^^^^^^^^ | | | `self` escapes the associated function body here | argument requires that `'1` must outlive `'static` For more information about this error, try `rustc --explain E0521`.
问题是
ctors
在 for 循环中属于 &Vec<Box<dyn Ctor + 'static>>
类型,而 &Box<Fn...>
也实现了 Fn...
所以你用 clone_box
的 T
调用 &Box<Fn...>
解决方案是摆脱那个额外的参考:
impl Clone for SVConstructor {
fn clone(&self) -> Self {
let Self { ctors } = self;
let mut new_ctors: Vec<Box<dyn Ctor + 'static>> = Vec::new();
for ctor in ctors {
let value: Box<dyn Ctor + 'static> = (*ctor).clone_box();
drop(ctor);
new_ctors.push(value);
}
Self { ctors: new_ctors }
}
}