为什么这段代码不能编译?
use std::{fs, path::Path};
fn main() {
let dir = Path::new("../FileSystem");
if !dir.is_dir() {
println!("Is not a directory");
return;
}
for item in try!(fs::read_dir(dir)) {
let file = match item {
Err(e) => {
println!("Error: {}", e);
return;
}
Ok(f) => f,
};
println!("");
}
println!("Done");
}
这是我遇到的错误
error[E0308]: mismatched types
--> src/main.rs:11:17
|
11 | for item in try!(fs::read_dir(dir)) {
| ^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
|
= note: expected type `()`
found type `std::result::Result<_, _>`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
我也尝试了问号运算符:
for item in fs::read_dir(dir)? {
有一个不同的错误:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:11:17
|
11 | for item in fs::read_dir(dir)? {
| ^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
以前的 Rust 版本中也有一个类似于 std::ops::Carrier
的错误。
我应该避免使用 try!()
和 ?
吗?处理错误的最佳方式是什么?大多数情况下,我会这样做:
match error_prone {
Err(e) => {
println!("Error: {}", e);
return;
},
Ok(f) => f,
};
但是如果我必须在 for
循环中使用它,那就会变得一团糟
for i in match error_prone {
// match code
} {
// loop code
}
try!
是一个宏,可以自动返回Err
。由于main
函数没有返回值,所以不能在该函数中使用try!
。 - Veedracmain
中调用它,该函数返回Result<T, Box<Error>>
,然后在main
中使用unwrap
或处理它。 - Veedracpath
是什么类型? - Veedrac