【问题标题】:How to check whether a path exists?如何检查路径是否存在?
【发布时间】:2015-09-03 20:09:57
【问题描述】:

貌似是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`

【问题讨论】:

标签: rust


【解决方案1】:

请注意,很多时候您想对文件做某事,比如阅读它。在这些情况下,尝试打开它并处理Result 会更有意义。这消除了a race condition between "check to see if file exists" and "open file if it exists"。如果你真正关心的是它是否存在......

锈 1.5+

Path::exists... 存在:

use std::path::Path;

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

As mental points out, Path::exists 只是calls fs::metadata for you:

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

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

【讨论】:

  • @Juxhin 通常是最难找到的简单答案! ^_^
  • 确实如此。我会理解您想要做的不仅仅是验证检查的场景,但是由于我现在只是让自己习惯了语言,所以我想慢慢地让自己接触标准 API,因为我以前从未深入研究过这种编程范式.再次感谢:-)
  • 值得一提的是Path::existsfs::metadata(path).is_ok()的别名
【解决方案2】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-28
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2014-02-20
    • 2020-05-08
    相关资源
    最近更新 更多