这个“静态”的一生来自何处?

时间:2018-08-03 02:14:57

标签: rust lifetime

The following program无法编译:

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正在创建需求吗?

1 个答案:

答案 0 :(得分:3)

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

  

模拟动态类型的类型。

     

大多数类型实现Any。但是,任何包含非'static引用的类型都不会。有关更多详细信息,请参见module-level documentation

特征本身需要绑定'static

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

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

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