【发布时间】: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