Search code examples
rustrust-macros

The std documentation examples with question marks don't compile


I'm having extreme difficulties with the try! and ? macro to the point that I'm starting to question the very fabric of reality. I lifted the example below straight from the rust-docs and it still blows up in my face.

Code:

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

fn main() {
    let mut file: File = File::open("foo.txt")?;
    file.write_all(b"Hello, world!")?;
}

Error:

error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
--> src/main.rs:6:23
|
6 |     let mut file: File = File::open("foo.txt")?;
|                          ----------------------
|                          |
|                          the trait `std::ops::Try` is not implemented for `()`
|                          in this macro invocation
|
= note: required by `std::ops::Try::from_error`

error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
--> src/main.rs:7:2
|
7 |     file.write_all(b"Hello, world!")?;
|     ---------------------------------
|     |
|     the trait `std::ops::Try` is not implemented for `()`
|     in this macro invocation
|
= note: required by `std::ops::Try::from_error`

I'm on the latest stable release of Rust according to rustup (1.19.0)


Solution

  • These examples are currently expected to be run wrapped in a function returning a Result; if you click Run in the upper right corner of the example, you will see that it expands to:

    fn main() {
        use std::fs::File;
        use std::io::prelude::*;
    
        fn foo() -> std::io::Result<()> {
            let mut file = File::create("foo.txt")?;
            file.write_all(b"Hello, world!")?;
            Ok(())
        }
    }
    

    This is because functions returning Results (like File::create and io::Write::write_all) should be handled with possible errors in mind (which is especially important in documentation examples).

    There was an RFC to allow returning Result from main() that was already merged, though the issue to allow ?s in main() is still active.