首页 > 解决方案 > 生命周期必须对静态生命周期有效

问题描述

trait X {}

trait Y {}

struct A {}

impl X for A {}

struct B<'r> {
    x: &'r mut Box<dyn X + 'r>,
    id: i32,
}

impl <'r> Y for B<'r> {}


struct Out {
    x: Box<dyn X>,
}

impl Out {
    pub fn new() -> Self {
        return Out {
            x: Box::new(A{})
        }
    }

    pub fn get_data(&mut self) -> Box<dyn Y> {
        return Box::new(B{
            id: 1,
            x: &mut self.x
        })
    }
}

操场上运行它。

我从编译器得到这个注释:

note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected &mut std::boxed::Box<dyn X>
              found &mut std::boxed::Box<(dyn X + 'static)>

我了解静态生命周期的来源,但在创建接受任何通用生命周期的结构 B 期间,不会将相同的生命周期传递给它。

[在以下答案后编辑]

我还尝试使 struct Out 通用,但在初始化后无法使用它。

标签: rust

解决方案


I fixed it (playground). Here's the relevant code:

// note the lifetime!
struct Out<'a> {
    x: Box<dyn X + 'a>,
}

// note the lifetime!
impl<'a> Out<'a> {
    pub fn new() -> Self {
        return Out {
            x: Box::new(A{})
        }
    }

    pub fn get_data(&'a mut self) -> Box<dyn Y + 'a> {
        return Box::new(B {
            id: 1,
            x: &mut self.x,
        })
    }
}

Why is this necessary?

Trait objects always have a lifetime. If no lifetime is specified or inferred, it defaults to 'static. Therefore you have to make Out generic over its lifetime and use it in the implementation.


推荐阅读