Rust errors: Difference between revisions

From wikinotes
Line 23: Line 23:
The result type is an enum, whose options <code>Ok, Err</code> have been merged into the global scope through <code>prelude</code>.
The result type is an enum, whose options <code>Ok, Err</code> have been merged into the global scope through <code>prelude</code>.


Example.
Given this Result producing code:
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
struct MyError {
struct MyError {

Revision as of 18:11, 8 February 2023

Rust has two primary methods of handling errors.

  • panic!() halts/exits the program
  • Result types are for handle-able errors

panic

  • intended for halting application, not control flow
  • have backtraces
panic!("tried to X but couldn't Y")

// convert panic to result
// (not intended for native rust code)
let result = panic::catch_unwind(|| {
    panic!("oh no!");
});

Result

The result type is an enum, whose options Ok, Err have been merged into the global scope through prelude.

Given this Result producing code:

struct MyError {
    value: isize
}

fn is_one(i: isize) -> Result<String, MyError> {
    if i == 1 {
        Ok("success".to_string())

    } else {
        Err(MyError{value: i})
    }
}

You can treat this like Option using match:

let result = match is_one(2) {
    Ok(x) => format!("horay: {}", x),
    Err(_) => panic!("an error occurred")
};
println!("{}", result);

But there are more concise ways of handling this

// panic if error, otherwise return value
let result = is_one(2)
    .unwrap()

// panic with message if error, otherwise return value
let result = is_one(2)
    .expect("an error occurred!")  // <-- panic message