【问题标题】:the lifetime must be valid for the static lifetime生命周期必须对静态生命周期有效
【发布时间】:2019-11-11 10:40:48
【问题描述】:
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
        })
    }
}

在操场上运行here

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

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


    【解决方案1】:

    我修复了它 (playground)。以下是相关代码:

    // 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,
            })
        }
    }
    

    为什么需要这样做?

    特征对象总是有生命周期的。如果没有指定或推断生命周期,则默认为'static。因此,您必须在其生命周期内使 Out 泛型并在实现中使用它。

    【讨论】:

    • 我想到了这个,但是当尝试使用 struct Out 时,我得到了borrowed value does not live long enough。更新了操场的使用情况。谢谢
    • 我看不到任何变化。我认为您创建了一个新的游乐场链接,但仍然需要更新问题以插入新链接。
    • 是的,现在更新的链接是play.rust-lang.org/…
    • 我无法修复它,我也不完全确定它为什么会发生。它甚至可能是一个编译器错误。你可以在 Reddit (/r/rust) 或 users.rust-lang.org 上询问。在这些论坛上,有些人比我更有经验。
    猜你喜欢
    • 2018-02-12
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 2015-08-26
    相关资源
    最近更新 更多