对 Vec<_>的可变引用在 while 循环中活得不够长

发布于 01-18 05:21 字数 899 浏览 2 评论 0原文

这是到目前为止的代码,相关行是 27 和 28: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=37bba701ad2e9d47741da1149881ddd1

错误消息:

error[E0597]: `neighs` does not live long enough
  --> src/lib.rs:28:25
   |
17 |     while let Some(Reverse(current)) = open.pop() {
   |                                        ---------- borrow later used here
...
28 |         for neighbor in neighs.iter_mut() {
   |                         ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
38 |     }
   |     - `neighs` dropped here while still borrowed

我过去使用过 Rust 几次,我我完全意识到这个问题应该是多么基本。我还花了几个小时尝试不同的事情并搜索类似的问题。我似乎无法找到解决方案。如何使 neighs 与函数 a_star 一样长?

Here's the code so far, the relevant lines are 27 and 28: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=37bba701ad2e9d47741da1149881ddd1

Error message:

error[E0597]: `neighs` does not live long enough
  --> src/lib.rs:28:25
   |
17 |     while let Some(Reverse(current)) = open.pop() {
   |                                        ---------- borrow later used here
...
28 |         for neighbor in neighs.iter_mut() {
   |                         ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
38 |     }
   |     - `neighs` dropped here while still borrowed

I used Rust a few times in the past, and I'm fully aware of how basic this problem should be. I've also spent hours trying different things and googling similar problems. I just can't seem to find a solution. How do I make neighs live as long as function a_star?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里寻她2025-01-25 05:21:16

我建议:

  1. 在 open 中存储 Cell 的副本,而不是对 Cell 的引用
open.push(Reverse(start.clone()));

  1. 将 Cell 结构的父字段设置为 Box 或 Rc 而不是引用:
#[derive(Clone, Eq)]
pub struct Cell {
    coords: (u32, u32),
    g_cost: u32,
    h_cost: u32,
    parent: Option<std::rc::Rc<Cell>>,
}

这种方式 open 将不会引用任何 neighs 元素或 current 元素。这将避免终身问题。

I would suggest:

  1. Store copies of Cell in open instead of references to Cell
open.push(Reverse(start.clone()));

  1. Make the parent field of the Cell struct a Box or Rc instead of reference:
#[derive(Clone, Eq)]
pub struct Cell {
    coords: (u32, u32),
    g_cost: u32,
    h_cost: u32,
    parent: Option<std::rc::Rc<Cell>>,
}

This way open will not reference any of neighs elements or current. which will avoid lifetime issues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文