O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Early returns and the try! macro

Here's another pattern for error handling: returning early from a function when an error occurs in any operation. We'll modify the earlier code that converts bytestring to String into this pattern:

fn bytestring_to_string_with_match(str: Vec<u8>) -> Result<String, FromUtf8Error> {     let ret = match String::from_utf8(str) {         Ok(str) => str.to_uppercase(),         Err(err) => return Err(err)     };     println!("Conversion succeeded: {}", ret);     Ok(ret) } 

The try! macro abstracts this pattern, making it possible to write this in a more concise way:

fn bytestring_to_string_with_try(str: Vec<u8>) -> Result<String, FromUtf8Error> {     let ret = try!(String::from_utf8(str));     println!("Conversion succeeded: {}", ret);  Ok(ret) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required