Rust for Pythonistas

Lesson 11 of 26

Option instead of None

In Python any variable can be None, and you only find out when the program runs and something crashes. Rust puts "maybe missing" into the type: Option<i32> is either Some(3) or None.

Option is just an enum with two variants, like the ones in lesson 10. That is why you handle it with match, and why the compiler knows when you forgot the None case. An Option<i32> is not an i32: you cannot add to it or print it as a number until you say what should happen when it is empty.

Optional[int] and Option<i32>

A function that sometimes has nothing to return. In Python the hint is Optional[int], but nothing stops you from ignoring it. In Rust the return type is Option<i32> and the value is built with Some(...) or None.

Python
from typing import Optional

def half(n: int) -> Optional[int]:
    if n % 2 == 0:
        return n // 2
    return None

for n in [8, 7]:
    h = half(n)
    if h is None:
        print(f"{n} is odd")
    else:
        print(f"half of {n} is {h}")
Rust
fn half(n: i32) -> Option<i32> {
    if n % 2 == 0 {
        Some(n / 2)
    } else {
        None
    }
}

fn main() {
    for n in [8, 7] {
        match half(n) {
            Some(h) => println!("half of {n} is {h}"),
            None => println!("{n} is odd"),
        }
    }
}
Output
half of 8 is 4
7 is odd

Python finds out at run time, Rust does not

The Python function returns None for an odd number, and the next line adds 1 to it. Python only sees the problem while running, and stops with a TypeError.

The Rust version does not compile until you say what to do with None. Here the code says "use 0". unwrap_or is the same idea as dict.get(key, default) or x or default: take the value if there is one, otherwise use the default.

Python
def half(n):
    if n % 2 == 0:
        return n // 2
    return None

n = 7
print(half(n) + 1)
Rust
fn half(n: i32) -> Option<i32> {
    if n % 2 == 0 {
        Some(n / 2)
    } else {
        None
    }
}

fn main() {
    let n = 7;
    let h = half(n).unwrap_or(0);
    println!("{}", h + 1);
}
Output
1

The short ways: if let, is_some, map

Not every case needs a full match. if let Some(x) = ... handles just the value case and does nothing otherwise, like a plain if x is not None.

.is_some() and .is_none() give a bool (they are opposites). .map(...) runs your closure on the value only when there is one, and leaves None alone.

Python
maybe = 7
nothing = None

if maybe is not None:
    print(f"got {maybe}")

if maybe is not None:
    print("maybe has a value")
else:
    print("maybe is empty")

doubled = nothing * 2 if nothing is not None else None
print(f"doubled: {doubled}")
print(f"or zero: {doubled if doubled is not None else 0}")
Rust
fn main() {
    let maybe = Some(7);
    let nothing: Option<i32> = None;

    if let Some(x) = maybe {
        println!("got {x}");
    }

    if maybe.is_some() {
        println!("maybe has a value");
    } else {
        println!("maybe is empty");
    }

    let doubled = nothing.map(|x| x * 2);
    println!("doubled: {doubled:?}");
    println!("or zero: {}", doubled.unwrap_or(0));
}
Output
got 7
maybe has a value
doubled: None
or zero: 0

? means "return None now"

Inside a function that returns Option, a ? after a value means: if this is None, return None from the whole function right away. It replaces the early return None checks that clutter Python code.

let ... else is the other new shape. Read it as "get the value out, or run this block", and that block must leave the function. Lesson 12 covers ? in more depth.

Python
def second_word(text):
    parts = text.split()
    if len(parts) < 2:
        return None
    return parts[1]

word = second_word("rust is fun")
if word is None:
    print("too short")
else:
    print(word)
Rust
fn second_word(text: &str) -> Option<&str> {
    let mut parts = text.split_whitespace();
    parts.next()?;
    parts.next()
}

fn main() {
    let Some(word) = second_word("rust is fun") else {
        println!("too short");
        return;
    };
    println!("{word}");
}
Output
is

Where you meet Option

Option shows up in the standard library wherever Python would return None, -1 or raise an IndexError. Three common places: Vec::get, max, and str::find.

Python
scores = [72, 91, 64]

if len(scores) > 9:
    print(f"tenth score: {scores[9]}")
else:
    print("no tenth score")

print(f"best: {max(scores)}")

text = "ferris the crab"
if "the" in text:
    print(f"found at {text.find('the')}")
else:
    print("not found")
Rust
fn main() {
    let scores = vec![72, 91, 64];
    let tenth = scores.get(9);

    match tenth {
        Some(s) => println!("tenth score: {s}"),
        None => println!("no tenth score"),
    }

    let best = scores.iter().max();
    println!("best: {}", best.unwrap_or(&0));

    let text = "ferris the crab";
    match text.find("the") {
        Some(i) => println!("found at {i}"),
        None => println!("not found"),
    }
}
Output
no tenth score
best: 91
found at 7

Where the Python analogy breaks

Cheat card

PythonRust
x: Optional[int] = Nonelet x: Option<i32> = None;
x = 5 # may be None laterlet x = Some(5);
if x is not None:if let Some(v) = x {
if x is None:if x.is_none() {
if x is not None:if x.is_some() {
d.get(key, default)map.get(&key).copied().unwrap_or(default)
x or 0x.unwrap_or(0)
x + 1 if x is not None else Nonex.map(|v| v + 1)
if x is None: return Nonelet v = x?;
assert x is not None # crashesx.unwrap() // crashes
assert x is not None, "no user"x.expect("no user") // crashes
match x: case None: ...match x { Some(v) => ..., None => ..., }

← Enums and match Result and ? instead of exceptions →