std::try! [] [src]

macro_rules! try {
    ($expr:expr) => (match $expr {
        $crate::result::Result::Ok(val) => val,
        $crate::result::Result::Err(err) => {
            return $crate::result::Result::Err($crate::convert::From::from(err))
        }
    })
}

Helper macro for unwrapping Result`Resultvalues while returning early with an error if the value of the expression isErr. Can only be used in functions that returnResultbecause of the early return ofErr` that it provides.

Examples

fn main() { use std::io; use std::fs::File; use std::io::prelude::*; fn write_to_file_using_try() -> Result<(), io::Error> { let mut file = try!(File::create("my_best_friends.txt")); try!(file.write_all(b"This is a list of my best friends.")); println!("I wrote to the file"); Ok(()) } // This is equivalent to: fn write_to_file_using_match() -> Result<(), io::Error> { let mut file = try!(File::create("my_best_friends.txt")); match file.write_all(b"This is a list of my best friends.") { Ok(_) => (), Err(e) => return Err(e), } println!("I wrote to the file"); Ok(()) } }
use std::io;
use std::fs::File;
use std::io::prelude::*;

fn write_to_file_using_try() -> Result<(), io::Error> {
    let mut file = try!(File::create("my_best_friends.txt"));
    try!(file.write_all(b"This is a list of my best friends."));
    println!("I wrote to the file");
    Ok(())
}
// This is equivalent to:
fn write_to_file_using_match() -> Result<(), io::Error> {
    let mut file = try!(File::create("my_best_friends.txt"));
    match file.write_all(b"This is a list of my best friends.") {
        Ok(_) => (),
        Err(e) => return Err(e),
    }
    println!("I wrote to the file");
    Ok(())
}