模式匹配io :: Result时出错

时间:2015-11-18 08:26:58

标签: rust

这是我的代码:

fn main() {
    use std::io::prelude::*;
    use std::fs::File;

    fn write_file() -> std::io::Result<()> {
        let mut f = try!(File::create("foo.txt"));
        try!(f.write_all(b"Hello, world!"));
    }

    match write_file() {
        Ok => println!("File was written"),
        Err(ex) => println!("{}", ex)
    };
}

我有一个错误:

src/main.rs:11:9: 11:11 error: this pattern has 0 fields, but the corresponding variant has 1 field [E0023]
src/main.rs:11         Ok => println!("File was written"),
                       ^~

为什么以及如何解决?

1 个答案:

答案 0 :(得分:6)

Ok => println!("File was written"),

应该是

Ok(()) => println!("File was written"),

因为Ok构造函数总是接受一个参数,即使该参数是()。如果您愿意,也可以使用Ok(_)