尝试!不会编译不匹配的类型

时间:2016-03-31 11:56:59

标签: macros rust

为什么这个Rust代码不能编译?

use std::fs;
use std::io;
use std::path::Path;

fn do_job(path: &Path) -> io::Result<()> {
    let mut files: Vec<&Path> = Vec::new();

    for entry in try!(fs::read_dir(path)) {
        entry = try!(entry);
    }
}

它与docs中的代码非常相似。

编译错误:

<std macros>:3:43: 3:46 error: mismatched types:
 expected `core::result::Result<std::fs::DirEntry, std::io::error::Error>`,
    found `std::fs::DirEntry`
(expected enum `core::result::Result`,
    found struct `std::fs::DirEntry`) [E0308]
<std macros>:3 $ crate:: result:: Result:: Ok ( val ) => val , $ crate:: result:: Result::
                                                         ^~~
src/main.rs:13:17: 13:28 note: in this expansion of try! (defined in <std macros>)
<std macros>:3:43: 3:46 help: run `rustc --explain E0308` to see a detailed explanation
src/main.rs:12:5: 14:6 error: mismatched types:
 expected `core::result::Result<(), std::io::error::Error>`,
    found `()`
(expected enum `core::result::Result`,
    found ()) [E0308]
src/main.rs:12     for entry in try!(fs::read_dir(path)) {
src/main.rs:13         entry = try!(entry);
src/main.rs:14     }
src/main.rs:12:5: 14:6 help: run `rustc --explain E0308` to see a detailed explanation

1 个答案:

答案 0 :(得分:2)

看起来你想为循环中的每个目录条目建立一个新的绑定:

for entry in fs::read_dir(path)? {
    let entry = entry?;
}

这个新绑定将影响for表达式中引入的绑定。

循环引入的entry类型为Result<DirEntry>,您尝试使用?(以前为try!)解包。但是,您尝试将结果DirEntry分配给类型为Result<DirEntry>的绑定,因此会出错。

第二个错误表示函数的返回值与声明的io::Result<()>类型不匹配。您只需返回Ok(())

即可
fn do_job(path: &Path) -> io::Result<()> {
    let mut files: Vec<&Path> = Vec::new();

    for entry in fs::read_dir(path)? {
        let entry = entry?;
        //process entry
    }
    Ok(())
}