Rust for Pythonistas

Lesson 19 of 26

Reading real code

Real code adds a few things the earlier lessons skipped: modules and use, attributes like #[derive], and syntax you only need to recognize, like lifetimes. This lesson ends with a realistic program that uses most of the course. It is the last lesson: if you can follow its program, you can follow a lot of everyday Rust.

Modules: mod, pub and use

A mod is a module, usually its own file (mod geometry; loads geometry.rs). Here it is written inline so it fits in one file. Everything in a module is private unless marked pub. Python only has the _name convention. use is import, and :: separates path parts the way . does in Python imports.

Python
import math


def circle_area(r):
    return math.pi * r * r



print(f"{circle_area(2.0):.2f}")
Rust
mod geometry {
    use std::f64::consts::PI;

    pub fn circle_area(r: f64) -> f64 {
        PI * r * r
    }
}

use geometry::circle_area;

fn main() {
    println!("{:.2}", circle_area(2.0));
}
Output
12.57

Lifetimes: recognize 'a, don't panic

'a (a tick plus a name) is a lifetime. It says that the returned reference is borrowed from the inputs, so it can't be used after they are gone. You will rarely write these, and for small changes you can read &'a str simply as &str. The <'a> after the name declares the label, just like <T> declares a generic type.

Python
def longest(a: str, b: str) -> str:
    return a if len(a) >= len(b) else b



print(longest("pear", "banana"))
Rust
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longest("pear", "banana"));
}
Output
banana

Putting it together: a realistic program

This program uses most of the course: a struct, a trait impl for printing, Result with ?, closures, match, if let and iterators. Go through it line by line using the marked lines. If you can follow it, you can follow a lot of everyday Rust.

Python
from dataclasses import dataclass


@dataclass
class Score:
    name: str
    points: int

    def __str__(self):
        return f"{self.name} ({self.points})"


def parse_line(line: str) -> Score:
    if "," not in line:
        raise ValueError("missing comma")
    name, points = line.split(",", 1)
    if not points.isdigit():
        raise ValueError(f'bad number "{points}"')
    return Score(name, int(points))


DATA = """ann,82
bob,not-a-number
cid,95
dan"""

scores = []
for line in DATA.splitlines():
    try:
        scores.append(parse_line(line))
    except ValueError as e:
        print(f'skipping "{line}": {e}')
if scores:
    best = max(scores, key=lambda s: s.points)
    print(f"best: {best}")
Rust
use std::fmt;

#[derive(Debug)]
struct Score {
    name: String,
    points: u32,
}

impl fmt::Display for Score {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} ({})", self.name, self.points)
    }
}

fn parse_line(line: &str) -> Result<Score, String> {
    let (name, points) = line.split_once(',').ok_or("missing comma")?;
    let points = points.parse().map_err(|_| format!("bad number {points:?}"))?;
    Ok(Score { name: name.to_string(), points })
}

const DATA: &str = "ann,82
bob,not-a-number
cid,95
dan";

fn main() {
    let mut scores = Vec::new();
    for line in DATA.lines() {
        match parse_line(line) {
            Ok(score) => scores.push(score),
            Err(e) => println!("skipping {line:?}: {e}"),
        }
    }
    if let Some(best) = scores.iter().max_by_key(|s| s.points) {
        println!("best: {best}");
    }
}
Output
skipping "bob,not-a-number": bad number "not-a-number"
skipping "dan": missing comma
best: cid (95)

Where the Python analogy breaks

Cheat card

PythonRust
import jsonuse serde_json;
from .models import Useruse crate::models::User;
module.function()module::function()
def _helper(): ... # private by conventionfn helper() { } // private unless pub
@dataclass#[derive(Debug, Clone, PartialEq)]
def __str__(self): ...impl fmt::Display for Score { }
raise ValueError("bad")return Err("bad".into());
def f(x: T) -> T: # TypeVarfn f<T>(x: T) -> T { }
# (no equivalent)fn f<'a>(x: &'a str) -> &'a str { }
async def f(): await g()async fn f() { g().await; }
# many names, one objectRc<T> / Arc<T> // shared ownership
pyproject.toml / uv.lockCargo.toml / Cargo.lock
uv add requestscargo add reqwest
python -m pytestcargo test

← Tests, builds and shipping Memory without a garbage collector →