Rust for Pythonistas

Lesson 12 of 26

Result and ? instead of exceptions

In Python a function can fail without saying so. int("x") looks like any other call, then it raises ValueError, and you find out by running it or by reading the docs. Rust puts the failure in the return type: Result<T, E> means "either a value of type T, or an error of type E".

Result is an enum with two variants, like the enums in lesson 10:

  • Ok(value): it worked, here is the value.
  • Err(error): it failed, here is the error.

So you can see which functions can fail just by reading their signature. You also cannot use the value without opening the Result first, so nothing is silently ignored. Two tools open it: match when you handle both cases here, and ? when you want the error to travel up to the caller, the way an exception does.

Option<T> from lesson 11 is a close cousin: it is either Some(value) or None, "a value or nothing". Result is "a value or an error", and the error can say what went wrong.

panic! is the other kind of failure: it stops the whole program right there, like a raise that nobody catches. You will see it in code that treats a bug as unrecoverable.

Parsing gives a Result, not an exception

int(text) and parse do the same job, but Rust hands the outcome back as a value. match then takes it apart, one arm per variant.

Python
for text in ["42", "4x2"]:
    try:
        n = int(text)
        print(f"parsed {n}")
    except ValueError:
        print("not a number")
Rust
fn main() {
    for text in ["42", "4x2"] {
        match text.parse::<i32>() {
            Ok(n) => println!("parsed {n}"),
            Err(_) => println!("not a number"),
        }
    }
}
Output
parsed 42
not a number

The ? operator lets the error travel up

Python code often lets an exception bubble up through several functions, and catches it once at the top. ? does exactly that, but the signatures show it.

Read ? as: "If this is an Err, return it from this function right now. Otherwise give me the value inside the Ok."

The function must say in its return type that it can fail, otherwise ? does not compile.

Python
def read_number(text):
    n = int(text)
    return n * 2

def read_label(text):
    n = read_number(text)
    return f"label-{n}"

for text in ["21", "x"]:
    try:
        print(read_label(text))
    except ValueError:
        print("failed")
Rust
fn read_number(text: &str) -> Result<i32, std::num::ParseIntError> {
    let n: i32 = text.parse()?;
    Ok(n * 2)
}

fn read_label(text: &str) -> Result<String, std::num::ParseIntError> {
    let n = read_number(text)?;
    Ok(format!("label-{n}"))
}

fn main() {
    for text in ["21", "x"] {
        match read_label(text) {
            Ok(label) => println!("{label}"),
            Err(_) => println!("failed"),
        }
    }
}
Output
label-42
failed

unwrap, expect and unwrap_or

.unwrap() says "I am sure this is Ok, give me the value". On an Err it panics: the program stops and prints an error. That is the same as an exception you never catch. .expect("message") does the same but adds your message to the crash.

Neither is a way to handle errors. You meet them everywhere while reading Rust, mostly in examples and in code that has already checked the input. .unwrap_or(default) is the calm version: it uses a fallback instead of crashing.

Python
def to_number(text):
    try:
        n = int(text)
    except ValueError:
        raise ValueError("bad number")
    return n + 1

good = int("7")
also = int("8")
try:
    fallback = int("x")
except ValueError:
    fallback = 0
print(good, also, fallback)

try:
    print(to_number("x"))
except ValueError as e:
    print(e)
Rust
fn to_number(text: &str) -> Result<i32, String> {
    let n: i32 = text.parse().map_err(|_| String::from("bad number"))?;
    Ok(n + 1)
}

fn main() {
    let good: i32 = "7".parse().unwrap();
    let also: i32 = "8".parse().expect("8 is a number");
    let fallback: i32 = "x".parse().unwrap_or(0);
    println!("{good} {also} {fallback}");
    match to_number("x") {
        Ok(n) => println!("{n}"),
        Err(msg) => println!("{msg}"),
    }
}
Output
7 8 0
bad number

Your own error type is an enum

Standard errors like ParseIntError are fine until you need to say why something failed. Then you write an enum, exactly like lesson 10, and use it as the E in Result. Each variant is one kind of failure, and a variant can carry data.

Python
class BadName(Exception):
    pass

def check_name(name):
    if not name:
        raise BadName("empty name")
    if len(name) > 5:
        raise BadName(f"too long: {len(name)} letters")
    return name.upper()

for name in ["ada", "", "lovelace"]:
    try:
        print(f"ok {check_name(name)}")
    except BadName as e:
        print(e)
Rust
#[derive(Debug)]
enum BadName {
    Empty,
    TooLong(usize),
}

fn check_name(name: &str) -> Result<String, BadName> {
    if name.is_empty() {
        return Err(BadName::Empty);
    }
    if name.len() > 5 {
        return Err(BadName::TooLong(name.len()));
    }
    Ok(name.to_uppercase())
}

fn main() {
    for name in ["ada", "", "lovelace"] {
        match check_name(name) {
            Ok(n) => println!("ok {n}"),
            Err(BadName::Empty) => println!("empty name"),
            Err(BadName::TooLong(n)) => println!("too long: {n} letters"),
        }
    }
}
Output
ok ADA
empty name
too long: 8 letters

main can return a Result too

fn main() may itself return a Result. Then you can use ? at the top level of the program, and no match is needed. On success, main must end with Ok(()).

The catch: if a ? really returns an Err, the program stops and exits with an error status. That is fine for a command-line tool, and it is what you will see in real code.

When there is more than one error type in one function, you will see Box<dyn std::error::Error> as the error type. Read it as "any error".

Python
try:
    count = int("3")
    price = float("2.5")
    print(f"{count} items at {price} = {count * price}")
except ValueError as e:
    print(f"error: {e}")
Rust
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let count: i32 = "3".parse()?;
    let price: f64 = "2.5".parse()?;
    println!("{count} items at {price} = {}", count as f64 * price);
    Ok(())
}
Output
3 items at 2.5 = 7.5

Where the Python analogy breaks

Cheat card

PythonRust
try: n = int(s) except ValueError: n = 0let n: i32 = s.parse().unwrap_or(0);
n = int(s) # may raiselet n: i32 = s.parse::<i32>()?;
raise ValueError("empty")return Err(BadName::Empty);
x = f() # may raiselet x = f()?;
try: print(f()) except ValueError as e: print(e)match f() { Ok(v) => println!("{v}"), Err(e) => println!("{e}"), }
n = int(s) # crashes on bad inputlet n: i32 = s.parse::<i32>().unwrap();
n = int(s) # crashes, with a messagelet n: i32 = s.parse().expect("need a number");
raise RuntimeError("boom")panic!("boom");
def f() -> int:fn f() -> Result<i32, ParseIntError>
def f() -> None: # may failfn f() -> Result<(), String>
x if x is not None else 0x.unwrap_or(0)

← Option instead of None Ownership and borrowing →