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
}
}
当我尝试编译上述代码时,出现以下错误。这里是 Playground link到代码
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.它还希望生命周期是“静态的”吗?学习这门语言真是令人沮丧。
最佳答案
主要问题是as_any
Function
中定义的方法。如果你看Any
documentation 中的特征定义,您将看到该特征的生命周期界限为 'static
。 params
领域 Function
生命周期为'a
它的生命周期不会像 'static
的生命周期那么长。一种解决方案是定义 params
字段为Box<Vec<Box<String>>>
,而不是使用引用并定义生命周期,但在没有进一步上下文的情况下,很难说。
关于rust - 使用Any时如何处理 "the type does not fulfill the required lifetime"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66625161/