[英]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
}
}
When I try compiling the above code I get the following error.当我尝试编译上述代码时,出现以下错误。 Here is the playground link to the code
这是代码的操场链接
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`
Why is Rust compiler getting confused about the struct lifetime, since I am just returning self.为什么 Rust 编译器对结构生命周期感到困惑,因为我只是返回 self. Also does it want the lifetime to be 'static.
它还希望生命周期是“静态的”吗? It's quite frustrating learning the language.
学习语言真是令人沮丧。
The main issue is the as_any
method defined in Function
.主要问题是
Function
中定义的as_any
方法。 If you look at the Any
trait definition in the documentation , you will see that the trait has a lifetime bound of 'static
.如果您查看文档中的
Any
特征定义,您会看到该特征的生命周期为'static
。 The params
field in Function
has a lifetime of 'a
which won't live as long as a lifetime of 'static
. Function
中的params
字段的生命周期为'a
,其生命周期不如'static
的生命周期。 One solution is to define the params
field as a Box<Vec<Box<String>>>
, instead of using a reference and defining a lifetime, but without further context, it is difficult to say.一种解决方案是将
params
字段定义为Box<Vec<Box<String>>>
,而不是使用引用并定义生命周期,但如果没有进一步的上下文,很难说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.