如何检查路径是否存在?

选择似乎是在 std::fs::PathExtstd::fs::metadata之间,但后者是建议目前,因为它是更稳定。下面是我一直在使用的代码,因为它是基于文档的:

use std::fs;


pub fn path_exists(path: &str) -> bool {
let metadata = try!(fs::metadata(path));
assert!(metadata.is_file());
}

然而,由于某些奇怪的原因,let metadata = try!(fs::metadata(path))仍然需要函数返回一个 Result<T,E>,即使我只是想返回一个如 assert!(metadata.is_file())所示的布尔值。

尽管这个问题很快就会有很多改变,但是我该如何绕过 try!()问题呢?

下面是相关的编译器错误:

error[E0308]: mismatched types
--> src/main.rs:4:20
|
4 |     let metadata = try!(fs::metadata(path));
|                    ^^^^^^^^^^^^^^^^^^^^^^^^ expected bool, found enum `std::result::Result`
|
= note: expected type `bool`
found type `std::result::Result<_, _>`
= note: this error originates in a macro outside of the current crate


error[E0308]: mismatched types
--> src/main.rs:3:40
|
3 |   pub fn path_exists(path: &str) -> bool {
|  ________________________________________^
4 | |     let metadata = try!(fs::metadata(path));
5 | |     assert!(metadata.is_file());
6 | | }
| |_^ expected (), found bool
|
= note: expected type `()`
found type `bool`
71688 次浏览

请注意,很多时候您希望对该文件执行 什么的操作,比如读取它。在这些情况下,尝试打开它并处理 Result更有意义。这样排除了 “检查文件是否存在”和“打开文件是否存在”之间的竞争条件。如果你只关心它是否存在。

生锈1.5 +

Path::exists... exists:

use std::path::Path;


fn main() {
println!("{}", Path::new("/etc/hosts").exists());
}

As mental points out, Path::exists simply 打电话给 fs::metadata找你:

pub fn exists(&self) -> bool {
fs::metadata(self).is_ok()
}

Rust 1.0 +

您可以检查 fs::metadata方法是否成功:

use std::fs;


pub fn path_exists(path: &str) -> bool {
fs::metadata(path).is_ok()
}


fn main() {
println!("{}", path_exists("/etc/hosts"));
}

你可以使用 std::path::Path::is_file:

use std::path::Path;


fn main() {
let b = Path::new("file.txt").is_file();
println!("{}", b);
}

Https://doc.rust-lang.org/std/path/struct . Path.html # method. is _ file