如何检查路径是否存在?

时间:2015-09-03 20:09:57

标签: rust

选择似乎在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`

2 个答案:

答案 0 :(得分:40)

请注意,很多时候你想用文件做某些事情,比如读它。在这些情况下,尝试打开它并处理Result更有意义。这消除了&#34之间的竞争条件;检查文件是否存在&#34;和&#34;打开文件(如果存在)&#34;。如果您真正关心的是它是否存在......

Rust 1.5 +

Path::exists ...存在:

use std::path::Path;

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

As mental points outPath::exists只是calls fs::metadata for you

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"));
}

答案 1 :(得分:2)

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

use std::path::Path;

fn main() {
   let o = Path::new("a.rs");
   let b = o.is_file();
   println!("{}", b);
}