Errors: Result and ?
Rust separates two kinds of errors:
- Unrecoverable errors: a programming mistake (an index outside the list, dividing integers by zero). The program stops with a panic.
- Expected errors: the file doesn’t exist, the user typed letters instead of a number. They’re returned with
Resultand the program decides what to do.
panic!
Section titled “panic!”fn main() { let v = vec![1, 2, 3]; println!("{}", v[10]); // panic: index out of bounds}When debugging with F5, Raxorin Studio stops on the line of the panic and shows you the variables at that moment. Without debugging, the message appears in Output with the file and line.
Result
Section titled “Result”Result is an enum with two options:
enum Result<T, E> { Ok(T), // it went well, with the value Err(E), // it went wrong, with the error}For example, converting text to a number can fail:
fn main() { let inputs = ["42", "hello", "-7"]; for text in inputs { match text.parse::<i32>() { Ok(n) => println!("{text} → {n}"), Err(e) => println!("{text} → error: {e}"), } }}unwrap and expect
Section titled “unwrap and expect”When you’re sure it can’t fail (or in a test program), unwrap() takes out the value and panics if it’s an error.
expect("message") is the same, but with your message:
fn main() { let n: i32 = "42".parse().unwrap(); let m: i32 = "7".parse().expect("it should be a number"); println!("{}", n + m);}The ? operator
Section titled “The ? operator”In a function that returns Result, ? means: “if it’s Err, return it now; if it’s Ok, continue with the value”.
It saves a lot of matches:
use std::fs;use std::num::ParseIntError;
fn add(a: &str, b: &str) -> Result<i32, ParseIntError> { let x: i32 = a.trim().parse()?; // if it fails, add returns the error let y: i32 = b.trim().parse()?; Ok(x + y)}
fn read_config() -> Result<String, std::io::Error> { let text = fs::read_to_string("config.txt")?; Ok(text.to_uppercase())}
fn main() { println!("{:?}", add("2", "3")); // Ok(5) println!("{:?}", add("2", "three")); // Err(ParseIntError { kind: InvalidDigit }) match read_config() { Ok(t) => println!("{t}"), Err(e) => println!("Couldn't read config.txt: {e}"), }}? also works with Option in functions that return Option.
Your own errors
Section titled “Your own errors”For your own errors, an enum with one option per case:
use std::fmt;
#[derive(Debug)]enum SaleError { NotFound(String), OutOfStock { left: u32 },}
// Display: how the error is shown to a person.impl fmt::Display for SaleError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SaleError::NotFound(p) => write!(f, "we don't have “{p}”"), SaleError::OutOfStock { left } => write!(f, "only {left} left"), } }}
fn sell(product: &str, quantity: u32) -> Result<u32, SaleError> { let stock = match product { "bread" => 5, _ => return Err(SaleError::NotFound(product.to_string())), }; if quantity > stock { return Err(SaleError::OutOfStock { left: stock }); } Ok(stock - quantity)}
fn main() { for (p, q) in [("bread", 2), ("bread", 9), ("milk", 1)] { match sell(p, q) { Ok(left) => println!("Sold. {left} left."), Err(e) => println!("Couldn't sell: {e}"), } }}The Shop sample uses exactly this pattern. For bigger programs, the thiserror (to define
errors) and anyhow (to propagate them easily) packages are in Packages → Recommended.