簡體   English   中英

對 Vec<_> 的可變引用在 while 循環中的壽命不夠長

[英]Mutable reference to Vec<_> does not live long enough in while loop

這是到目前為止的代碼,相關行是 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與 function a_star一樣長?

我會建議:

  1. 將 Cell 的副本存儲在 open 中而不是對 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 元素或當前元素。 這將避免終身問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM