如何启用?替代生锈的功能?

时间:2019-04-08 22:48:51

标签: rust

考虑以下示例

use std::fs::File;
use std::io::{BufRead, BufReader, Result};

fn main() {

    let file = File::open("myfile.txt")?; // This doesn't work
    let file = File::open("myfile.txt").unwrap();  // this works
    for line in BufReader::new(file).lines() {
        println!("{}", line.unwrap());
    }
}

使用rustc 1.33.0 (2aa4c46cf 2019-02-28)

我正在尝试使用?代替展开,但似乎总是得到^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use theoperator in a function that returns() ,有人可以为我指明方向吗?

谢谢

1 个答案:

答案 0 :(得分:2)

?运算符仅在返回Result<T, E>的函数中起作用,因为expr?本质上与以下内容相同:

match expr {
  Ok(value) => value,
  Err(err) => return Err(err),
}

您可以修改main()函数以返回结果。使用Result<(), Box<dyn std::error::Error>>将使您可以在实现?特征的任何标准错误类型上使用Error

use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() -> Result<(), Box<dyn Error>> {
    let file = File::open("myfile.txt")?; // this will now work
    for line in BufReader::new(file).lines() {
        println!("{}", line?);
    }

    // finally, we need to end with Ok(()) since we no longer have
    // the default return type ()
    Ok(())
}