Files
100-exercises-to-learn-rust/book/src/05_ticket_v2/07_unwrap.md
Luca Palmieri 96f06708b0 Render the book in PDF using pandoc and LaTeX. (#126)
* Render the book in PDF using `pandoc` and LaTeX.

* Fix installs.

* Go the apt-get route

* Another attempt

* Avoid installing twice.

* Re-order.

* Add more packages.

* Minimise deps. Fix link checker.

* Missing package.

* Missing package.

* Missing package.

* More packages.

* Missing package.

* Missing package.

* More packages...

* Remove.

* Fix link checker.

* Fix link checker.

* Fix path.

* Add subtitle.

* Avoid running over the right margin.

* Avoid running over the right margin.

* Formatting
2024-08-05 17:52:15 +02:00

1.3 KiB
Raw Blame History

Unwrapping

Ticket::new now returns a Result instead of panicking on invalid inputs.
What does this mean for the caller?

Failures cant be (implicitly) ignored

Unlike exceptions, Rusts Result forces you to handle errors at the call site.
If you call a function that returns a Result, Rust wont allow you to implicitly ignore the error case.

fn parse_int(s: &str) -> Result<i32, ParseIntError> {
    // ...
}

// This won't compile: we're not handling the error case.
// We must either use `match` or one of the combinators provided by 
// `Result` to "unwrap" the success value or handle the error.
let number = parse_int("42") + 2;

You got a Result. Now what?

When you call a function that returns a Result, you have two key options:

  • Panic if the operation failed. This is done using either the unwrap or expect methods.

    // Panics if `parse_int` returns an `Err`.
    let number = parse_int("42").unwrap();
    // `expect` lets you specify a custom panic message.
    let number = parse_int("42").expect("Failed to parse integer");
  • Destructure the Result using a match expression to deal with the error case explicitly.

    match parse_int("42") {
        Ok(number) => println!("Parsed number: {}", number),
        Err(err) => eprintln!("Error: {}", err),
    }