Rust File示例无法编译

时间:2017-06-21 06:16:27

标签: rust

Rust file examples似乎没有使用Rust 1.18.0进行编译。

example

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!");
}

错误日志:

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

2 个答案:

答案 0 :(得分:7)

?是一个检查Result的语法糖:如果结果为Err,则返回,就像一样。如果没有错误(又名Ok),则函数继续。当你输入这个:

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

    let _ = File::open("foo.txt")?;
}

这意味着:

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

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

然后您了解到目前为止,您无法在main中使用?,因为main返回单位()而不是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
    }
}

PS:主要工作?proposition

答案 1 :(得分:4)

他们编译。他们只是不在这样的main函数中编译。如果你看一下这些例子,他们都有一个很大的&#34; Run&#34;他们的按钮。点击它,它会在围栏上打开完整,完整的示例。

您上面使用的那个扩展为此代码:

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

    fn foo() -> std::io::Result<()> {
        let mut file = File::open("foo.txt")?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)?;
        assert_eq!(contents, "Hello, world!");
        Ok(())
    }
}

该代码无法编译,因为您已将代码传播Result到一个函数(在这种情况下为main)并且不会返回{{ 1}}。

相关问题