gpt4 book ai didi

rust - 生命周期必须对静态生命周期有效

转载 作者:行者123 更新时间:2023-11-29 08:30:39 25 4
gpt4 key购买 nike

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在 Playground 上。

我从编译器那里得到这条注释:

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 的创建过程中并没有将相同的生命周期传递给接受任何通用生命周期的结构 B。

[在下面的答案后编辑]

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

最佳答案

我修复了它 ( 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,
})
}
}

为什么这是必要的?

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

关于rust - 生命周期必须对静态生命周期有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58799788/

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