gpt4 book ai didi

rust - 编译器建议我添加一个 'static lifetime because the parameter type may not live long enough, but I don' t think that's what I want

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

我正在尝试实现类似于这个最小示例的东西:

trait Bar<T> {}

struct Foo<T> {
data: Vec<Box<Bar<T>>>,
}

impl<T> Foo<T> {
fn add<U: Bar<T>>(&mut self, x: U) {
self.data.push(Box::new(x));
}
}

由于 Rust 默认为(据我所知)传递所有权,我的心智模型认为这应该可行。 add方法取得对象的所有权 x并能够将此对象移动到 Box 中因为它知道完整类型 U (而不仅仅是特征 Bar<T> )。一旦搬进Box ,盒子内项目的生命周期应该与盒子的实际生命周期相关联(例如,当 pop() 离开向量时,对象将被销毁)。

然而,很明显,编译器不同意(而且我肯定比我知道的更多......),要求我考虑添加一个 'static生命周期限定符 (E0310)。我 99% 确定这不是我想要的,但我不确定我应该做什么。

为了澄清我的想法并帮助识别误解,我的心智模型来自 C++ 背景,是:

  • Box<T>本质上是 std::unique_ptr<T>
  • 没有任何注释,如果Copy,变量按值传递和右值引用否则
  • 带有引用注释,&大致是 const&&mut大致是 &
  • 默认生命周期是词法作用域

最佳答案

检查整个错误:

error[E0310]: the parameter type `U` may not live long enough
--> src/main.rs:9:24
|
8 | fn add<U: Bar<T>>(&mut self, x: U) {
| -- help: consider adding an explicit lifetime bound `U: 'static`...
9 | self.data.push(Box::new(x));
| ^^^^^^^^^^^
|
note: ...so that the type `U` will meet its required lifetime bounds
--> src/main.rs:9:24
|
9 | self.data.push(Box::new(x));
| ^^^^^^^^^^^

具体来说,编译器让您知道某些任意类型 U 可能包含引用,然后该引用可能变得无效:

impl<'a, T> Bar<T> for &'a str {}

fn main() {
let mut foo = Foo { data: vec![] };

{
let s = "oh no".to_string();
foo.add(s.as_ref());
}
}

那将是个坏消息。

无论您想要'static 生命周期还是参数化生命周期都取决于您的需要。 'static 生命周期更容易使用,但有更多限制。因此,当您在结构或类型别名中声明 trait 对象 时,它是默认值:

struct Foo<T> {
data: Vec<Box<dyn Bar<T>>>,
// same as
// data: Vec<Box<dyn Bar<T> + 'static>>,
}

但是,当用作参数时,特征对象使用生命周期省略并获得唯一的生命周期:

fn foo(&self, x: Box<dyn Bar<T>>)
// same as
// fn foo<'a, 'b>(&'a self, x: Box<dyn Bar<T> + 'b>)

这两件事需要匹配。

struct Foo<'a, T> {
data: Vec<Box<dyn Bar<T> + 'a>>,
}

impl<'a, T> Foo<'a, T> {
fn add<U>(&mut self, x: U)
where
U: Bar<T> + 'a,
{
self.data.push(Box::new(x));
}
}

struct Foo<T> {
data: Vec<Box<dyn Bar<T>>>,
}

impl<T> Foo<T> {
fn add<U>(&mut self, x: U)
where
U: Bar<T> + 'static,
{
self.data.push(Box::new(x));
}
}

关于rust - 编译器建议我添加一个 'static lifetime because the parameter type may not live long enough, but I don' t think that's what I want,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349574/

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