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

The ? operator

A shorter way of writing try! macros is available with the ? operator. With that, the preceding function can become even tidier:

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

This operator becomes even nicer if you have a combined statement of several operations, where a failure in each operator should mean a failure of the whole. For instance, we could merge the whole by opening a file, reading a file, and converting it to uppercase into a single line:

File::create("foo.txt")?.write_all(b"Hello world!") 

This operator got into the stable release in version 1.13. In its current form, ...

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