我有一个包装了Box<dyn Any>
个构造函数的VEC的 struct ,我已经断言它是克隆的.
我有一个性状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())
// }
// }
当我取消对我得到的一切的 comments 时:
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`.