-4

Consider the following example

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());
    }
}

using rustc 1.33.0 (2aa4c46cf 2019-02-28)

I am trying to use ? to substitute unwrap, but it seems like I always get ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the?operator in a function that returns() , can someone point me a direction?

Thanks

Jal
  • 2,174
  • 1
  • 18
  • 37
  • https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#propagating-errors, https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#the--operator-can-only-be-used-in-functions-that-return-result – melpomene Apr 08 '19 at 23:07

1 Answers1

2

The ? operator only works inside functions that return Result<T, E>, since expr? is essentially the same as:

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

You can modify your main() function to return a result though. Using Result<(), Box<dyn std::error::Error>> will allow you to use ? on any standard error type that implements the Error trait:

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(())
}
Frxstrem
  • 38,761
  • 9
  • 79
  • 119