gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:42:05 25 4
gpt4 key购买 nike

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
}
}
当我尝试编译以上代码时,出现以下错误。这是代码的操场 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编译器对struct的生存期感到困惑,因为我只是返回self。它还希望生命周期是“静态的”。学习语言实在令人沮丧。

最佳答案

主要问题是在as_any中定义的Function方法。如果查看documentation中的Any特性定义,您将看到该特性的生命周期范围为'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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com