gpt4 book ai didi

file-io - 无法找出 Rust 中奇怪的 Path 行为

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

我正在编写一个读取 Path 并返回 DirEntry 实例的函数。有一些我不明白的奇怪行为。

pub fn file_to_direntry<T: AsRef<Path>>(filepath: T) -> Result<DirEntry, Box<Error>> {
match filepath.has_parent() {
Some(parent) => {
//..
}
// has no parent
// this line would cause an error
// Err(Error { repr: Os { code: 2, message: "No such file or directory" } })
None => path_to_entry(Path::new("."), path),
}
}


fn path_to_entry<A: AsRef<Path>, B: AsRef<Path>>(path: A, filename: B) -> Result<DirEntry, Box<Error>> {
let filename: &Path = filename.as_ref();
let path: &Path = path.as_ref();

// this line prints, "" "."
println!("{:?} {:?}", path, PathBuf::from("."));

// when I replace this line to
// for entry in try!(read_dir(PathBuf::from(".")))
// it works perfectly fine

for entry in try!(read_dir(path)) {
println!("{:?}", try!(entry));
}
Err(From::from("no file found"))
}

Full code on the Rust playground

最佳答案

在您的示例代码中,您使用 PathBuf::from("todos.txt") 进行测试。这是一个相对路径,它不包括起始 /c:\

当您执行 let parent = pf.parent(); 时,它将返回 Some("")。所以 parent 是一个空字符串,不是 Some("."),也不是 Noneparent如果路径以根或前缀终止,将只返回 None。在上面的示例中,您只包含了 None 部分,但不会调用它。

read_dir如果提供的路径不存在,将返回错误。当你传递一个像 read_dir(PathBuf::from("")) 这样的空字符串时就是这种情况,但是如果你使用 read_dir(PathBuf::from(". ")).

关于file-io - 无法找出 Rust 中奇怪的 Path 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41585143/

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