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.
import math
def circle_area(r):
return math.pi * r * r
print(f"{circle_area(2.0):.2f}")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));
}12.57Lifetimes: 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.
def longest(a: str, b: str) -> str:
return a if len(a) >= len(b) else b
print(longest("pear", "banana"))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"));
}bananaPutting 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.
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}")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}");
}
}skipping "bob,not-a-number": bad number "not-a-number"
skipping "dan": missing comma
best: cid (95)Where the Python analogy breaks
- Lifetimes like
'ahave no Python version. They don't change how long anything lives. They only tell the compiler which input a returned reference points into. asynccomes without an event loop. Python shipsasyncio; Rust needs a runtime crate such astokioto run anasync fn.- Generics are checked.
fn f<T>(x: T)may only use what its bounds allow: to printxit needsT: Display. A PythonTypeVaris only a hint. - Shared ownership is opt-in.
RcandArclet many names own one value, as Python does all the time, but the value is read-only unless you addRefCellorMutex.
Cheat card
| Python | Rust |
|---|---|
import json | use serde_json; |
from .models import User | use crate::models::User; |
module.function() | module::function() |
def _helper(): ... # private by convention | fn 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: # TypeVar | fn 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 object | Rc<T> / Arc<T> // shared ownership |
pyproject.toml / uv.lock | Cargo.toml / Cargo.lock |
uv add requests | cargo add reqwest |
python -m pytest | cargo test |
← Tests, builds and shipping Memory without a garbage collector →