Rust File示例无法编译

ale*_*ett 2 rust

Rust 文件示例似乎没有使用Rust 1.18.0编译.

对于例如:

use std::fs::File;
use std::io::prelude::*;
fn main() {
    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    assert_eq!(contents, "Hello, world!");
}
Run Code Online (Sandbox Code Playgroud)

错误日志:

rustc 1.18.0 (03fc9d622 2017-06-06)
error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied
 --> <anon>:4:20
  |
4 |     let mut file = File::open("foo.txt")?;
  |                    ----------------------
  |                    |
  |                    the trait `std::ops::Carrier` is not implemented for `()`
  |                    in this macro invocation
  |
  = note: required by `std::ops::Carrier::from_error`

error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied
 --> <anon>:6:5
  |
6 |     file.read_to_string(&mut contents)?;
  |     -----------------------------------
  |     |
  |     the trait `std::ops::Carrier` is not implemented for `()`
  |     in this macro invocation
  |
  = note: required by `std::ops::Carrier::from_error`

error: aborting due to 2 previous errors
Run Code Online (Sandbox Code Playgroud)

Fre*_*ios 7

?是一个语法糖,它检查Result:如果结果是Err,它就像是一样返回.如果没有错误(aka Ok),则该功能继续.当你输入这个:

fn main() {
    use std::fs::File;

    let _ = File::open("foo.txt")?;
}
Run Code Online (Sandbox Code Playgroud)

这意味着:

fn main() {
    use std::fs::File;

    let _ = match File::open("foo.txt") {
        Err(e)  => return Err(e),
        Ok(val) => val,
    };
}
Run Code Online (Sandbox Code Playgroud)

然后你明白,现在,你不能?在主要使用,因为主要返回单位()而不是Result.如果你想要这些东西工作,你可以把它放在一个函数中,它返回一个Result并从main检查它:

fn my_stuff() -> std::io::Result<()> {
    use std::fs::File;
    use std::io::prelude::*;

    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    // do whatever you want with `contents`
    Ok(())
}


fn main() {
    if let Err(_) = my_stuff() {
        // manage your error
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:有一个主要工作的主张?.