最佳答案
选择似乎是在 std::fs::PathExt
和 std::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`