【问题标题】:Multiple borrow in previous iteration of loop在循环的前一次迭代中多次借用
【发布时间】:2019-04-23 09:22:23
【问题描述】:

以下是我正在处理的代码,我用队列探索目录路径,我想将文件系统树存储在我的数据结构中(枚举 Entry):

use failure::Error;
use std::collections::VecDeque;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

fn main() -> Result<(), Error> {
    let paths = visit_dir(Path::new(".")).map_err(Error::from)?;
    Ok(())
}

#[derive(Debug)]
enum Entry {
    Dir(PathBuf, Vec<Entry>),
    File(PathBuf),
}

impl Entry {
    fn new_dir(path: &Path) -> Entry {
        Entry::Dir(path.to_path_buf(), Vec::new())
    }

    fn new_file(path: &Path) -> Entry {
        Entry::File(path.to_path_buf())
    }

    /// Append a new Entry to self if self is a directory.
    fn push(&mut self, path: &Path) -> Option<&mut Entry> {
        if let Entry::Dir(_, ref mut content) = self {
            let entry = if path.is_dir() {
                Entry::new_dir(path)
            } else {
                Entry::new_file(path)
            };
            content.push(entry);
            return content.last_mut();
        }
        None
    }

    fn path(&self) -> &Path {
        match self {
            Entry::Dir(path, _) => path,
            Entry::File(path) => path,
        }
    }
}

fn visit_dir(root: &Path) -> io::Result<Entry> {
    let mut dir = Entry::new_dir(root);
    let mut queue = VecDeque::new();
    queue.push_back(&mut dir);

    while !queue.is_empty() {
        let parent = queue.pop_front().unwrap();
        let path = parent.path();
        if path.is_dir() {
            for entry in fs::read_dir(path)? {
                let entry = entry?;
                let path = entry.path();
                let entry = parent.push(&path).unwrap();

                if path.is_dir() {
                    queue.push_back(entry);
                }
            }
        }
    }

    Ok(dir)
}

链接到Playground

我得到的错误是:

error[E0499]: cannot borrow `*parent` as mutable more than once at a time
  --> src/main.rs:61:29
   |
61 |                 let entry = parent.push(&path).unwrap();
   |                             ^^^^^^ mutable borrow starts here in previous iteration of loop

我的问题是:

  • 为什么会出现此错误?
  • 有什么办法可以解决吗?

【问题讨论】:

  • play.rust-lang.org/…,但这很不清楚你想用你的 push 函数做什么
  • @Stargateur 如果我没记错的话,那是行不通的。您正在克隆值,通过这样做,函数返回的条目将看不到循环更新的值。

标签: loops rust borrow-checker


【解决方案1】:
  • entry 在行中可变地借用parent:

    let entry = parent.push(&path).unwrap();
    
  • 那么,你不释放entry,因为你将它存储在queue中。因此,当这是循环中的第二次迭代时,parent 仍然是可变借用的。这样做是不安全的。

您正在尝试做的是可变引用树。这在 Rust 中是行不通的,这通常是个坏主意。你应该修改你想要实现的方式。

【讨论】:

  • 如果我 use recursion 我可以毫无问题地填充相同的数据结构。你知道是否有更好的方法(尤其是没有递归)来达到同样的效果?
  • @Nick 你的用例是什么?
  • 我需要重新创建两个目录的文件系统数据结构,然后比较它们的内容。
  • 因为它可能导致堆栈溢出。
  • 你有没有堆栈溢出?打一个是假设性的。
猜你喜欢
  • 2023-01-10
  • 2014-10-11
  • 2021-05-15
  • 1970-01-01
  • 2021-05-22
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多