gpt4 book ai didi

Rust - 由于需求冲突,无法推断出 autoref 的适当生命周期

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

我是 Rust 的生命周期概念的新手,无法全神贯注于一段特定的代码。我一直在使用 Rust 的 SDL 绑定(bind)及其 Texture/TextureCreator 类,问题基本上归结为以下方案:

struct Creator;

impl Creator {
fn create(&self) -> Creature {
Creature { creator: &self }
}
}

struct Creature<'a> {
creator: &'a Creator,
}

struct MyStruct<'a> {
creator: Creator,
creatures: Vec<Creature<'a>>,
}

impl<'a> MyStruct<'a> {
fn new() -> MyStruct<'a> {
MyStruct {
creatures: Vec::new(),
creator: Creator,
}
}

fn create(&mut self) {
let new_creature = self.creator.create();
self.creatures.push(new_creature);
}
}

fn main() {
let mut my_struct = MyStruct::new();
my_struct.create();
}

实际问题出在MyStruct::create里面方法。如果我尝试编译上面的代码,我会得到:

error[E0495]: cannot infer an appropriate lifetime for autoref due to con
flicting requirements
--> src/main.rs:27:41
|
27 | let new_creature = self.creator.create();
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 define
d on the method body at 26:5...
--> src/main.rs:26:5
|
26 | / fn create(&mut self) {
27 | | let new_creature = self.creator.create();
28 | | self.creatures.push(new_creature);
29 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:27:28
|
27 | let new_creature = self.creator.create();
| ^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on t
he impl at 18:6...
--> src/main.rs:18:6
|
18 | impl<'a> MyStruct<'a> {
| ^^
= note: ...so that the expression is assignable:
expected Creature<'a>
found Creature<'_>

有趣的是,当我在 MyStruct::create 中注释掉这一行时:

self.creatures.push(new_creature);

它编译得很好。

我的假设是它会导致以下问题 - 新创建的 new_creature引用了 creator属于my_struct .现在,如果new_creature然后由 creatures 拥有向量,我真的不能在 my_struct 上调用任何方法借用自己作为 mut因为那时会有:

  • 引用creator里面my_struct
  • my_struct 的可变引用在方法体内(因此到 my_struct.creator )

不过,这是我个人的看法。从编译器的角度来看,它是关于生命周期的,但不太明白。所以我有以下两个问题:

  1. 为什么在这种情况下编译器会提示生命周期?
  2. 我怎样才能开始存储 Vec<Creature>在结构中?我是否应该确保不同时保留 CreatorVec<Creature>在同一结构中以避免上述问题?

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