首页 > 解决方案 > 这个“静态”的生命是从哪里来的?

问题描述

以下程序无法编译:

use std::any::Any;

trait Foo<'a> {
    fn to_box_any(self: Box<Self>) -> Box<Any + 'a>;
}

fn test<'a>(v: Box<dyn Foo<'a> + 'a>) {
    v.to_box_any();
}

fn main() {}

错误信息:

error[E0478]: lifetime bound not satisfied
 --> src/main.rs:8:7
  |
8 |     v.to_box_any();
  |       ^^^^^^^^^^
  |
note: lifetime parameter instantiated with the lifetime 'a as defined on the function body at 7:1
 --> src/main.rs:7:1
  |
7 | fn test<'a>(v: Box<dyn Foo<'a> + 'a>) {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = note: but lifetime parameter must outlive the static lifetime

我以为我标记了尽可能多的显式生命周期,但我不知道static生命周期要求来自哪里。

如果我Any使用自定义特征进行更改,它会起作用,所以看起来像是Any在创建需求?

标签: rustlifetime

解决方案


我强烈建议您阅读您尝试使用的代码的文档。例如,文档Any说(强调我的)

一种模拟动态类型的类型。

大多数类型实现Any. 但是,任何包含非'static引用的类型都不会。有关更多详细信息,请参阅模块级文档

特征本身需要一个'static界限:

pub trait Any: 'static {
    fn get_type_id(&self) -> TypeId;
}

您还可以看到所有方法实现需要'static

impl Any + 'static {}
impl Any + 'static + Send {}
impl Any + 'static + Sync + Send {}

推荐阅读