Rust for Pythonistas

Python → Rust phrasebook

PythonRustLesson
uv init hellocargo new helloYour first Rust project
uv run hellocargo runYour first Rust project
mypy srccargo checkYour first Rust project
# no build stepcargo build // program in target/debug/Your first Rust project
pyproject.tomlCargo.tomlYour first Rust project
[project][package]Your first Rust project
dependencies = [][dependencies]Your first Rust project
def main(): ...fn main() { }Your first Rust project
if __name__ == "__main__": main()// not needed: Rust starts at main()Your first Rust project
.venv/target/Your first Rust project
def greet(name: str) -> str:pub fn greet(name: &str) -> String {A tiny app: a function and a module
return f"Hello, {name}!"format!("Hello, {name}!") // last line, no ;A tiny app: a function and a module
# new file src/hello/greeting.py// new file src/greeting.rs, plus "mod greeting;" in main.rsA tiny app: a function and a module
from hello.greeting import greetuse greeting::greet;A tiny app: a function and a module
greeting.greet("Ada")greeting::greet("Ada")A tiny app: a function and a module
def _helper(): ... # private by conventionfn helper() { } // private unless pubA tiny app: a function and a module
print(greet("Ada"))println!("{}", greet("Ada"));A tiny app: a function and a module
print("hi")println!("hi");Hello, variables and mut
print(f"{x} and {y}")println!("{x} and {y}");Hello, variables and mut
print(f"{x + 1}")println!("{}", x + 1);Hello, variables and mut
print(repr(items))println!("{:?}", items);Hello, variables and mut
s = f"{x}!"let s = format!("{x}!");Hello, variables and mut
x = 5let x = 5;Hello, variables and mut
x = 5 x += 1let mut x = 5; x += 1;Hello, variables and mut
n: int = 5let n: i32 = 5;Hello, variables and mut
MAX = 100 # by conventionconst MAX: u32 = 100;Hello, variables and mut
# comment// commentHello, variables and mut
"""docstring"""/// doc commentHello, variables and mut
if __name__ == "__main__":fn main() { }Hello, variables and mut
x = 5 · ratio = 0.5let x: i32 = 5; · let ratio: f64 = 0.5;Numbers and strings
n = 200 # 0..255let n: u8 = 200;Numbers and strings
big = 10_000_000_000let big: i64 = 10_000_000_000;Numbers and strings
i = len(items) # index typelet i: usize = items.len();Numbers and strings
7 / 2 # 3.5 · 7 // 2 # 37.0 / 2.0 · 7 / 2 // 3, cuts toward zeroNumbers and strings
float(x) · int(x)x as f64 · x as i32Numbers and strings
len(s) # characterss.len() // bytes · s.chars().count()Numbers and strings
s.upper() · s.strip()s.to_uppercase() · s.trim()Numbers and strings
sub in s · s.split(",")s.contains(sub) · s.split(',')Numbers and strings
f"{a}!" · s += "!"format!("{a}!") · s.push_str("!")Numbers and strings
s = "hi"let s: &str = "hi"; // borrowed view · let mut s = String::from("hi"); // ownedNumbers and strings
True · c = "x"true · let c: char = 'x';Numbers and strings
def add(a: int, b: int) -> int:fn add(a: i32, b: i32) -> i32 {Functions and expressions
return a + ba + b // last expression, no semicolonFunctions and expressions
return x # early exitreturn x;Functions and expressions
def f() -> None:fn f() { // returns ()Functions and expressions
def f(x, y=1):no default args; write a second function or pass every valueFunctions and expressions
f(x=1, y=2)f(1, 2) // no keyword argumentsFunctions and expressions
a if c else bif c { a } else { b }Functions and expressions
value = 1 + 2let value = { 1 + 2 }; // a block is an expressionFunctions and expressions
f(1) # callf(1);Functions and expressions
def main(): ...fn main() { ... }Functions and expressions
lambda x: x * 2|x| x * 2 // closure, lesson 8Functions and expressions
print(f(1))println!("{}", f(1));Functions and expressions
if x > 0:if x > 0 {if, loops and ranges
elif x == 0:} else if x == 0 {if, loops and ranges
else:} else {if, loops and ranges
if items:if !items.is_empty() {if, loops and ranges
for i in range(5):for i in 0..5 {if, loops and ranges
for i in range(1, 6):for i in 1..=5 {if, loops and ranges
for i in range(0, 10, 2):for i in (0..10).step_by(2) {if, loops and ranges
for i in range(5, 0, -1):for i in (1..=5).rev() {if, loops and ranges
while n > 0:while n > 0 {if, loops and ranges
while True:loop {if, loops and ranges
breakbreak;if, loops and ranges
continuecontinue;if, loops and ranges
nums = [1, 2, 3]let nums = vec![1, 2, 3];Vec and HashMap
nums = []let mut nums: Vec<i32> = Vec::new();Vec and HashMap
nums.append(4)nums.push(4);Vec and HashMap
len(nums)nums.len()Vec and HashMap
nums.sort()nums.sort();Vec and HashMap
nums[1:3]&nums[1..3]Vec and HashMap
x in numsnums.contains(&x)Vec and HashMap
for x in nums:for x in &nums {Vec and HashMap
d["a"] = 1d.insert("a", 1);Vec and HashMap
d.get("a")d.get("a") // Some(v) or NoneVec and HashMap
del d["a"]d.remove("a");Vec and HashMap
Counter(xs)*counts.entry(x).or_insert(0) += 1;Vec and HashMap
[x * 2 for x in xs]xs.iter().map(|x| x * 2).collect::<Vec<_>>()Iterators and closures
[x for x in xs if x > 0]xs.iter().filter(|x| **x > 0).collect::<Vec<_>>()Iterators and closures
lambda x: x * 2|x| x * 2Iterators and closures
def f(x): print(x) return x * 2|x| { println!("{x}"); x * 2 }Iterators and closures
sum(xs)let total: i32 = xs.iter().sum();Iterators and closures
max(xs), min(xs)xs.iter().max(), xs.iter().min() // Option, lesson 11Iterators and closures
sum(1 for x in xs if x > 0)xs.iter().filter(|x| **x > 0).count()Iterators and closures
for i, x in enumerate(xs):for (i, x) in xs.iter().enumerate() {Iterators and closures
for x, y in zip(a, b):for (x, y) in a.iter().zip(b.iter()) {Iterators and closures
any(x > 0 for x in xs)xs.iter().any(|x| *x > 0)Iterators and closures
all(x > 0 for x in xs)xs.iter().all(|x| *x > 0)Iterators and closures
reversed(xs)xs.iter().rev()Iterators and closures
class Point: def __init__(self, x, y): self.x = x self.y = ystruct Point { x: i32, y: i32, }Structs and impl
p = Point(1, 2)let p = Point::new(1, 2);Structs and impl
def total(self):fn total(&self) -> i32 {Structs and impl
def add(self, k): self.n += kfn add(&mut self, k: i32) { self.n += k; }Structs and impl
p = Counter() p.add(1) # changes plet mut p = Counter::new(); p.add(1);Structs and impl
@staticmethod @classmethodfn origin() -> Self { // no self, call with Type::origin()Structs and impl
self.xself.xStructs and impl
print(repr(p))#[derive(Debug)] + println!("{:?}", p);Structs and impl
a == b#[derive(PartialEq)] + a == bStructs and impl
copy.copy(p)p.clone() // needs #[derive(Clone)]Structs and impl
class Meters: self.value = vstruct Meters(f64); // read with .0Structs and impl
class Point: # importable from other filespub struct Point { // visible to other filesStructs and impl
class Status(Enum): OPEN = "open"enum Status { Open, }Enums and match
Status.OPENStatus::OpenEnums and match
Status.OPEN.name # "OPEN"match status { Status::Open => "Open", ... }Enums and match
match x: case 1:match x { 1 => ...Enums and match
case 0:0 => ...Enums and match
case 1 | 2:1 | 2 => ...Enums and match
case 3 | 4 | 5 | 6 | 7 | 8 | 9:3..=9 => ...Enums and match
case n if n < 0:n if n < 0 => ...Enums and match
case _:_ => ...Enums and match
isinstance(s, Circle)Shape::Circle(r) => ...Enums and match
result = describe(x)let result = match x { ... };Enums and match
def cents(self): # in the Enum classimpl Coin { fn cents(&self) -> u32 { ... } }Enums and match
x: Optional[int] = Nonelet x: Option<i32> = None;Option instead of None
x = 5 # may be None laterlet x = Some(5);Option instead of None
if x is not None:if let Some(v) = x {Option instead of None
if x is None:if x.is_none() {Option instead of None
if x is not None:if x.is_some() {Option instead of None
d.get(key, default)map.get(&key).copied().unwrap_or(default)Option instead of None
x or 0x.unwrap_or(0)Option instead of None
x + 1 if x is not None else Nonex.map(|v| v + 1)Option instead of None
if x is None: return Nonelet v = x?;Option instead of None
assert x is not None # crashesx.unwrap() // crashesOption instead of None
assert x is not None, "no user"x.expect("no user") // crashesOption instead of None
match x: case None: ...match x { Some(v) => ..., None => ..., }Option instead of None
try: n = int(s) except ValueError: n = 0let n: i32 = s.parse().unwrap_or(0);Result and ? instead of exceptions
n = int(s) # may raiselet n: i32 = s.parse::<i32>()?;Result and ? instead of exceptions
raise ValueError("empty")return Err(BadName::Empty);Result and ? instead of exceptions
x = f() # may raiselet x = f()?;Result and ? instead of exceptions
try: print(f()) except ValueError as e: print(e)match f() { Ok(v) => println!("{v}"), Err(e) => println!("{e}"), }Result and ? instead of exceptions
n = int(s) # crashes on bad inputlet n: i32 = s.parse::<i32>().unwrap();Result and ? instead of exceptions
n = int(s) # crashes, with a messagelet n: i32 = s.parse().expect("need a number");Result and ? instead of exceptions
raise RuntimeError("boom")panic!("boom");Result and ? instead of exceptions
def f() -> int:fn f() -> Result<i32, ParseIntError>Result and ? instead of exceptions
def f() -> None: # may failfn f() -> Result<(), String>Result and ? instead of exceptions
x if x is not None else 0x.unwrap_or(0)Result and ? instead of exceptions
b = a # same list, two nameslet b = a; // moved: a is unusable nowOwnership and borrowing
b = a.copy()let b = a.clone();Ownership and borrowing
y = x # intlet y = x; // numbers are copiedOwnership and borrowing
def f(items: list[int]): ...fn f(items: &[i32]) { }Ownership and borrowing
def f(items: list[int]): ... # changes itfn f(items: &mut Vec<i32>) { }Ownership and borrowing
def f(name: str): ...fn f(name: &str) { }Ownership and borrowing
f(items) # might change itf(&items) // can only readOwnership and borrowing
f(items) # changes itf(&mut items) // may changeOwnership and borrowing
# (no equivalent: Python has no pointers)*n += 1; // change the value behind a &mutOwnership and borrowing
# garbage collector frees later// freed at the owner's closing }Ownership and borrowing
class Dog: # duck typingimpl Describe for Dog { fn describe(&self) -> String { ... } }Traits instead of duck typing
class Describe(Protocol): ...trait Describe { fn describe(&self) -> String; }Traits instead of duck typing
def show(item: Describe):fn show(item: &impl Describe)Traits instead of duck typing
def show[T: Describe](item: T):fn show<T: Describe>(item: &T)Traits instead of duck typing
class Base: def describe(self): return "base"trait Describe { fn describe(&self) -> String { String::from("base") } }Traits instead of duck typing
def __str__(self): ...impl std::fmt::Display for X { fn fmt(...) -> std::fmt::Result }Traits instead of duck typing
def __repr__(self): ...#[derive(Debug)] // print with {:?}Traits instead of duck typing
def __eq__(self, other): ...#[derive(PartialEq)] // a == bTraits instead of duck typing
copy.copy(x)x.clone() // needs #[derive(Clone)]Traits instead of duck typing
hasattr(x, "describe")T: Describe // checked at compile timeTraits instead of duck typing
items = [Circle(), Square()]let items: Vec<Box<dyn Shape>> = ...;Traits instead of duck typing
def __add__(self, other): ...impl std::ops::Add for X { type Output = X; ... }Traits instead of duck typing
TypeError # at run timeerror[E0308]: mismatched typesReading compiler errors
NameError # at run timeerror[E0425]: cannot find valueReading compiler errors
AttributeError # at run timeerror[E0599]: no method named ... foundReading compiler errors
x = 1 x = 2 # always allowederror[E0384]: cannot assign twice to immutable variableReading compiler errors
items.append(x) # always allowederror[E0596]: cannot borrow as mutableReading compiler errors
b = a # shares the listerror[E0382]: borrow of moved valueReading compiler errors
# change a list while looping over iterror[E0502]: cannot borrow as mutable because it is also borrowed as immutableReading compiler errors
match x: # no case _ is fineerror[E0004]: non-exhaustive patternsReading compiler errors
# duck typing fails at call timeerror[E0277]: the trait bound ... is not satisfiedReading compiler errors
mypy app.pycargo check // fast: errors only, no buildReading compiler errors
help(thing)rustc --explain E0382Reading compiler errors
sys.argvstd::env::args() // the program comes first, like argv[0]Building and running a real program
sys.argv[1]env::args().nth(1) // an OptionBuilding and running a real program
argparse / clickclap // a crateBuilding and running a real program
python main.py notes.txtcargo run -- notes.txtBuilding and running a real program
open(path).read()fs::read_to_string(&path) // a ResultBuilding and running a real program
for line in sys.stdin:for line in io::stdin().lines() {Building and running a real program
os.environ.get("NAME", "x")env::var("NAME").unwrap_or(String::from("x"))Building and running a real program
print(msg, file=sys.stderr)eprintln!("{msg}");Building and running a real program
sys.exit(main())fn main() -> ExitCode { ... }Building and running a real program
sys.exit(2)std::process::exit(2);Building and running a real program
# no build stepcargo run --release -- notes.txtBuilding and running a real program
two [project.scripts]src/bin/stats.rs + cargo run --bin statsBuilding and running a real program
uv init shopcargo new shopCargo in depth: dependencies and workspaces
uv run shopcargo runCargo in depth: dependencies and workspaces
mypy .cargo checkCargo in depth: dependencies and workspaces
pyproject.toml / uv.lockCargo.toml / Cargo.lockCargo in depth: dependencies and workspaces
[project] dependencies = [...][dependencies]Cargo in depth: dependencies and workspaces
[dependency-groups] dev = [...][dev-dependencies]Cargo in depth: dependencies and workspaces
requires-python = ">=3.12"rust-version = "1.85"Cargo in depth: dependencies and workspaces
"pydantic[email]~=2.0"serde = { version = "1", features = ["derive"] }Cargo in depth: dependencies and workspaces
uv add requestscargo add reqwestCargo in depth: dependencies and workspaces
uv lock --upgradecargo updateCargo in depth: dependencies and workspaces
uv treecargo treeCargo in depth: dependencies and workspaces
__main__.py / __init__.pysrc/main.rs / src/lib.rsCargo in depth: dependencies and workspaces
import shop.models # file found automaticallymod models; // declare the file, then useCargo in depth: dependencies and workspaces
.venv/ __pycache__/ dist/target/Cargo in depth: dependencies and workspaces
PyPI / Read the Docscrates.io / docs.rsCargo in depth: dependencies and workspaces
pytestcargo testTests, builds and shipping
pytest -k negativecargo test negativeTests, builds and shipping
pytest -scargo test -- --nocaptureTests, builds and shipping
def test_add():#[test] fn add_works() { }Tests, builds and shipping
assert a == bassert_eq!(a, b);Tests, builds and shipping
assert okassert!(ok);Tests, builds and shipping
with pytest.raises(ValueError): ...#[should_panic] // or assert!(r.is_err());Tests, builds and shipping
"""Docstring. >>> add(2, 2)"""/// Doc comment with a ``` code blockTests, builds and shipping
sphinx-build docs/ html/cargo doc --openTests, builds and shipping
ruff format / ruff checkcargo fmt / cargo clippyTests, builds and shipping
uv buildcargo build --releaseTests, builds and shipping
uv publishcargo publishTests, builds and shipping
uv tool install ruffcargo install ripgrepTests, builds and shipping
# C extension modulepyo3 + maturin // Rust inside a wheelTests, builds and shipping
import jsonuse serde_json;Reading real code
from .models import Useruse crate::models::User;Reading real code
module.function()module::function()Reading real code
def _helper(): ... # private by conventionfn helper() { } // private unless pubReading real code
@dataclass#[derive(Debug, Clone, PartialEq)]Reading real code
def __str__(self): ...impl fmt::Display for Score { }Reading real code
raise ValueError("bad")return Err("bad".into());Reading real code
def f(x: T) -> T: # TypeVarfn f<T>(x: T) -> T { }Reading real code
# (no equivalent)fn f<'a>(x: &'a str) -> &'a str { }Reading real code
async def f(): await g()async fn f() { g().await; }Reading real code
# many names, one objectRc<T> / Arc<T> // shared ownershipReading real code
pyproject.toml / uv.lockCargo.toml / Cargo.lockReading real code
uv add requestscargo add reqwestReading real code
python -m pytestcargo testReading real code
del xdrop(x);Memory without a garbage collector
def __del__(self): ...impl Drop for X { fn drop(&mut self) { ... } }Memory without a garbage collector
# freed when the refcount reaches 0// freed at the owner's closing }Memory without a garbage collector
gc.collect()// no garbage collectorMemory without a garbage collector
b = a # same list, two nameslet b = a; // moves the header, the items stayMemory without a garbage collector
b = a.copy()let b = a.clone(); // new heap memoryMemory without a garbage collector
class Node: next: "Node | None"struct Node { next: Option<Box<Node>> }Memory without a garbage collector
sys.getsizeof(x)std::mem::size_of::<T>()Memory without a garbage collector
_ = make() # a normal namelet _ = make(); // dropped at onceMemory without a garbage collector
a = b # any object, sharedlet a = Rc::clone(&b);Shared ownership: Rc, RefCell and Weak
a is bRc::ptr_eq(&a, &b)Shared ownership: Rc, RefCell and Weak
sys.getrefcount(x)Rc::strong_count(&x)Shared ownership: Rc, RefCell and Weak
obj.field = 1 # through any nameobj.borrow_mut().field = 1; // Rc<RefCell<T>>Shared ownership: Rc, RefCell and Weak
print(obj.field)println!("{}", obj.borrow().field);Shared ownership: Rc, RefCell and Weak
weakref.ref(obj)Rc::downgrade(&obj) // a Weak<T>Shared ownership: Rc, RefCell and Weak
ref() # the object or Noneweak.upgrade() // Some(rc) or NoneShared ownership: Rc, RefCell and Weak
gc.collect() # frees cycles// no cycle collector: break cycles with WeakShared ownership: Rc, RefCell and Weak
# threads share objectsArc<Mutex<T>> // Rc<RefCell<T>> for threadsShared ownership: Rc, RefCell and Weak
threading.Thread(target=f).start()let h = thread::spawn(move || f());Threads without a GIL
t.join()h.join().unwrap() // also gives the return valueThreads without a GIL
lock = threading.Lock() with lock: count += 1let count = Mutex::new(0); *count.lock().unwrap() += 1;Threads without a GIL
# the same object in many threadslet shared = Arc::clone(&data); // Arc<Mutex<T>>Threads without a GIL
with ThreadPoolExecutor() as pool:thread::scope(|s| { s.spawn(...); });Threads without a GIL
queue.Queue()let (tx, rx) = mpsc::channel();Threads without a GIL
q.put(x)tx.send(x).unwrap();Threads without a GIL
q.get()rx.recv().unwrap() // or: for x in rx { }Threads without a GIL
# GIL: one thread runs Python at a time// threads run in parallel; data races do not compileThreads without a GIL
json.dumps(obj, separators=(",", ":"))serde_json::to_string(&obj)?The crates you'll meet everywhere
json.dumps(obj, indent=2)serde_json::to_string_pretty(&obj)?The crates you'll meet everywhere
User(**json.loads(text))let user: User = serde_json::from_str(text)?;The crates you'll meet everywhere
@dataclass # or a pydantic model#[derive(Serialize, Deserialize)]The crates you'll meet everywhere
Field(alias="userName") # pydantic#[serde(rename = "userName")]The crates you'll meet everywhere
tags: list = field(default_factory=list)#[serde(default)]The crates you'll meet everywhere
raise RuntimeError("...") from eresult.context("...")? // anyhowThe crates you'll meet everywhere
except Exception as e:fn main() -> anyhow::Result<()>The crates you'll meet everywhere
class NotFound(ShopError): ...#[derive(Debug, Error)] enum ShopError { #[error("...")] NotFound }The crates you'll meet everywhere
raise BadQuantity() from eBadQuantity(#[from] ParseIntError) // then ? convertsThe crates you'll meet everywhere
argparse.ArgumentParser()#[derive(Parser)] struct Args { ... }The crates you'll meet everywhere
parser.add_argument("--times", type=int, default=1)#[arg(long, default_value_t = 1)] times: u32The crates you'll meet everywhere
parser.add_argument("--shout", action="store_true")#[arg(long)] shout: boolThe crates you'll meet everywhere
args = parser.parse_args()let args = Args::parse();The crates you'll meet everywhere
asyncio.run(main())#[tokio::main] async fn main() { }async/await vs asyncio
async def f(): ...async fn f() { }async/await vs asyncio
await f()f().awaitasync/await vs asyncio
await asyncio.sleep(0.5)tokio::time::sleep(Duration::from_millis(500)).await;async/await vs asyncio
await asyncio.gather(a(), b())tokio::join!(a(), b())async/await vs asyncio
task = asyncio.create_task(f())let handle = tokio::spawn(f());async/await vs asyncio
await taskhandle.await.unwrap()async/await vs asyncio
await asyncio.wait_for(f(), timeout=1)tokio::time::timeout(Duration::from_secs(1), f()).awaitasync/await vs asyncio
asyncio.wait(..., return_when=FIRST_COMPLETED)tokio::select! { ... }async/await vs asyncio
await asyncio.to_thread(blocking)tokio::task::spawn_blocking(blocking).awaitasync/await vs asyncio
except asyncio.CancelledError:// no exception: a dropped future just stopsasync/await vs asyncio
# a pure-Python module stats.pysrc/lib.rs with #[pymodule] fn stats(...)Rust inside Python with PyO3
def mean(values: list[float]) -> float:#[pyfunction] fn mean(values: Vec<f64>) -> f64 {Rust inside Python with PyO3
def greet(name=None):#[pyfunction] #[pyo3(signature = (name=None))] fn greet(name: Option<&str>) -> String {Rust inside Python with PyO3
raise ValueError("no values")return Err(PyValueError::new_err("no values"));Rust inside Python with PyO3
def f() -> int: # may raisefn f() -> PyResult<i64> {Rust inside Python with PyO3
class Counter:#[pyclass] struct Counter { ... }Rust inside Python with PyO3
def __init__(self, step=1):#[new] #[pyo3(signature = (step=1))] fn new(step: i64) -> Self {Rust inside Python with PyO3
@property def count(self): ...#[pyo3(get)] count: i64,Rust inside Python with PyO3
def __repr__(self): ...fn __repr__(&self) -> String {Rust inside Python with PyO3
list / dict / NoneVec<T> / HashMap<K, V> / Option<T>Rust inside Python with PyO3
pip install -e .maturin develop // again after every Rust changeRust inside Python with PyO3
python -m buildmaturin build --releaseRust inside Python with PyO3
all(p(c) for c in s)s.chars().all(|c| p(c))Reading real projects: uv, ruff and pydantic-core
next((x for x in xs if p(x)), None)xs.iter().find(|x| p(x))Reading real projects: uv, ruff and pydantic-core
x is not None and p(x)x.is_some_and(|v| p(v))Reading real projects: uv, ruff and pydantic-core
if x is None: raise MyError()x.ok_or_else(|| MyError::new())?Reading real projects: uv, ruff and pydantic-core
s.lower() == "yes"s.eq_ignore_ascii_case("yes")Reading real projects: uv, ruff and pydantic-core
"A" <= c <= "Z"matches!(c, b'A'..=b'Z')Reading real projects: uv, ruff and pydantic-core
def __exit__(self, *exc): ...impl Drop for Guard { fn drop(&mut self) { ... } }Reading real projects: uv, ruff and pydantic-core
@classmethod def from_str(cls, s): ...impl FromStr for X { fn from_str(s: &str) -> Result<Self, Self::Err> { ... } }Reading real projects: uv, ruff and pydantic-core
"".join(parts)let mut s = String::with_capacity(n); s.push(c);Reading real projects: uv, ruff and pydantic-core