Lựa chọn có vẻ là giữa std::fs::PathExt
và std::fs::metadata
, nhưng tùy chọn thứ hai được đề xuất trong thời gian vì nó ổn định hơn. Dưới đây là đoạn code tôi đã làm việc với khi nó được dựa trên các tài liệu:Cách kiểm tra xem đường dẫn có tồn tại không?
use std::fs;
pub fn path_exists(path: &str) -> bool {
let metadata = try!(fs::metadata(path));
assert!(metadata.is_file());
}
Tuy nhiên, vì một lý do kỳ quặc let metadata = try!(fs::metadata(path))
vẫn đòi hỏi các chức năng để trả lại một Result<T,E>
mặc dù tôi chỉ đơn giản muốn trở lại một boolean như từ assert!(metadata.is_file())
.
Mặc dù có thể sẽ có nhiều thay đổi đối với điều này đủ sớm, làm cách nào tôi bỏ qua sự cố try!()
?
Dưới đây là lỗi biên dịch có liên quan:
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`
Bạn đã thấy [câu hỏi liên quan này] (http://stackoverflow.com/questions/30555477/try-does-not-compile) về 'try!'? Hoặc phần [Rust Book] (https://doc.rust-lang.org/book/error-handling.html) về xử lý lỗi? – Shepmaster