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

Unwrapping

Writing the same match statements over and over again quickly becomes boilerplate code, which can make it nastier to read. The standard library contains a couple of helper methods that both Result and Option types implement. You can use them to simplify error cases where you really do not expect things to fail.

The methods are as follows:

  • unwrap(self): T expects self to be Ok/Some and returns the value contained within. If it's Err or None instead, it raises a panic with the contents of the error displayed.
  • expect(self, msg: &str): T behaves like unwrap, except that it outputs a custom message before panicking in addition to the contents of the error.
  • unwrap_or(self, opt_b: T): T behaves like unwrap, except that instead of panicking, ...

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