3
use std::io;
use std::fs::File;
use std::io::prelude::*;

fn main() {
    let mut csv = File::open("Item.csv")?;
}

this is some part of my code, and I've got error:

   Compiling eracsv v0.1.0 (file:///C:/Users/jwm/Project/eracsv)
error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
 --> src\main.rs:
  |
  |     let mut csv = File::open("Item.csv")?;
  |                   -----------------------
  |                   |
  |                   the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
  |                   in this macro invocation
  |
  = help: the trait `std::ops::Try` is not implemented for `()`
  = note: required by `std::ops::Try::from_error`

I have deal with both rustc 1.19 stable and 1.22 nightly and both discharging same error.

but, this is exactly same code as rust doc, isn't it? It is explicitly mentioned that File::open() function returns result .

I am curious why ? operator makes compile error while unwrap() doesn't.

Jang Whe-moon
  • 125
  • 1
  • 9

1 Answers1

9

What the error message is actually telling you is you're using the ? operator inside of a function that returns () (this being the main function). The ? operator propagates errors upwards, but it can only do that if the function it's used in actually has a compatible return type that can represent that error.

Or in other words, you can only use it in a function that itself is returning a Result (with a compatible error type). Your main does not return a Result, so you cannot use the ? operator inside of it.

You may also be interested in RFC 1937, which would allow the use of ? in main (by allowing you to declare that main returns a Result).

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347