[英]“the type does not fulfill the required lifetime” when using a method in a thread
[英]How to handle “the type does not fulfill the required lifetime” when using Any?
use std::any::Any;
pub enum ObjectType {
Error,
Function,
}
pub trait Object {
fn obj_type(&self) -> ObjectType;
// Required to downcast a Trait to specify structure
fn as_any(&self) -> &dyn Any;
}
#[derive(Debug)]
pub struct Function<'a> {
params: &'a Box<Vec<Box<String>>>,
}
impl<'a> Object for Function<'a> {
fn obj_type(&self) -> ObjectType {
ObjectType::Function
}
fn as_any(&self) -> &dyn Any {
self
}
}
当我尝试编译上述代码时,出现以下错误。 这是代码的操场链接
Compiling playground v0.0.1 (/playground)
error[E0477]: the type `Function<'a>` does not fulfill the required lifetime
--> src/lib.rs:27:9
|
27 | self
| ^^^^
|
= note: type must satisfy the static lifetime
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:27:9
|
27 | self
| ^^^^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 21:7...
--> src/lib.rs:21:7
|
21 | impl <'a>Object for Function<'a> {
| ^^
note: ...so that the type `Function<'a>` will meet its required lifetime bounds
--> src/lib.rs:27:9
|
27 | self
| ^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
--> src/lib.rs:27:9
|
27 | self
| ^^^^
= note: expected `&(dyn Any + 'static)`
found `&dyn Any`
为什么 Rust 编译器对结构生命周期感到困惑,因为我只是返回 self. 它还希望生命周期是“静态的”吗? 学习语言真是令人沮丧。
主要问题是Function
中定义的as_any
方法。 如果您查看文档中的Any
特征定义,您会看到该特征的生命周期为'static
。 Function
中的params
字段的生命周期为'a
,其生命周期不如'static
的生命周期。 一种解决方案是将params
字段定义为Box<Vec<Box<String>>>
,而不是使用引用并定义生命周期,但如果没有进一步的上下文,很难说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.