相关疑难解决方法(0)

为什么要试试!()和?在不返回Option或Result的函数中使用时不编译?

为什么这段代码不能编译?

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");
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

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: …
Run Code Online (Sandbox Code Playgroud)

rust

42
推荐指数
2
解决办法
7977
查看次数

标签 统计

rust ×1