Skip to content

Instantly share code, notes, and snippets.

@lamont-granquist
Last active December 6, 2022 22:35
Show Gist options
  • Save lamont-granquist/9d4889cac6a9736d5953bb940dc7ff11 to your computer and use it in GitHub Desktop.
Save lamont-granquist/9d4889cac6a9736d5953bb940dc7ff11 to your computer and use it in GitHub Desktop.
Rust error handling for the impatient

I really don't care at all: unwrap()

Just panics if the API returns a None or Err:

fs::create_dir(dir).unwrap();

I don't care but I want a slighly better message: expect()

Pretty much the same, also showing use of format! to render a string with some dynamic info:

fs::create_dir(dir).expect(&format!("couldn't create directory: {}", dir));

My function returns a compatible Result<T,E> and I just want to "throw" it up a level: '?' operator

fs::create_dir(dir)?;

I want to extract an Ok into a variable and throw my own error otherwise: let-else

let Ok(thing) = stuff else {
  return MyError::new(&format!("some error happened with {}", somestuff));
}

I just want the default value for the type: unwrap_or_default()

I just want to specify a default value (the type may not have a default): unwrap_or()

I Just want to specify the default value but not evaluate it every time: unwrap_or_else()

I want to discard an error and convert it to just an Option: ok()

I want to discard the result and just focus on the error with Option: err()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment