rust - 使用Any时如何处理 "the type does not fulfill the required lifetime"?

标签 rust traits lifetime

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 中的特征定义,您将看到该特征的生命周期界限为 'staticparams领域 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/

相关文章:

rust - 在实现返回可变引用的迭代器时,如何修复 “cannot infer an appropriate lifetime for autoref”?

rust - 摆脱生命周期的限制?

ubuntu - 为什么 Rust 编译器不能从拆分标准输入行中推断出来

random - 特征界限不满足库中的错误

scala - Scala 中的线性化顺序

generics - 为什么我不能在带有类型参数的特征上添加一揽子实现?

rust - 当我重新分配链表的一半时,不再引用的 block 会发生什么?

string - 在 Rust 中将字符串切片转换为 int

rust - 无法使用 CoerceUnsized 将嵌套大小的类型强制为未设置大小的类型

syntax - 当我想引用一个枚举的变体时,是否有办法停止重复该枚举的名称? [复制]