Try! and File::create - misunderstanding E0308


#1

The following contrived example runs:

use std::error::Error;
use std::fs::File;

#[allow(unused_variables, unused_mut)]
fn main() {
    let mut file = match File::create("hello.txt") {
        Err(why) => panic!("couldn't open {}: {}", "hello.txt",
                                                                   Error::description(&why)),
        Ok(file) => file,
};

}

I was hoping to use the try! macro to simplify as per the API documentation https://doc.rust-lang.org/stable/std/fs/struct.File.html

use std::fs::File;

#[allow(unused_variables, unused_mut)]
fn main() {
    let mut file = try!(File::create("hello.txt"));
}

But not joy.

Could someone help me understand the error in the expansion of try! reported by the compiler?

<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err ( 
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
<std macros>:1:1: 6:48 note: in expansion of try!
src\main.rs:5:20: 5:51 note: expansion site

Thanks a lot


#2

try! requires that the function return a Result.

If you click on the playpen link in the upper right of the example, you’ll see that it is actually wrapped in a function.

See this thread: Problem in the std::fs::File docs? Or a problem with me?