Lesson 14 of 26
Traits instead of duck typing
In Python you often do not say what a function needs. You just call item.describe() and trust
that the object has that method. That is duck typing: if it walks like a duck, it is a duck. A
typing.Protocol or an abc.ABC writes the expectation down, but Python checks it at run
time, or only in a type checker.
Rust makes it a rule. A trait is a named list of methods, and a type can only be used where the trait is
required if the compiler can see the matching impl. Four shapes to recognise:
trait X { ... }: the list of methods. Read it as a Protocol or an ABC.impl X for Y { ... }: Y provides them. Read it as "Y can do X".T: Xorimpl Xin a function: "any type that does X".Box<dyn X>: one value of some type that does X, where the exact type is only known at run time.
Many traits you already use have Python dunder twins: Display is __str__,
Debug is __repr__, PartialEq is __eq__,
Clone is a copy, and Add is __add__.
From duck typing to a trait
Two different types, one shared method. Python trusts that the method is there. Rust says it out loud with a trait, and then each type implements it.
class Dog:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} is a dog"
class Robot:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} is a robot"
for thing in [Dog("Rex"), Robot("R2")]:
print(thing.describe())trait Describe {
fn describe(&self) -> String;
}
struct Dog {
name: String,
}
impl Describe for Dog {
fn describe(&self) -> String {
format!("{} is a dog", self.name)
}
}
struct Robot {
name: String,
}
impl Describe for Robot {
fn describe(&self) -> String {
format!("{} is a robot", self.name)
}
}
fn main() {
let dog = Dog { name: String::from("Rex") };
let robot = Robot { name: String::from("R2") };
println!("{}", dog.describe());
println!("{}", robot.describe());
}Rex is a dog
R2 is a robotDefault methods are like methods on a base class
A trait can give a method a body. Then a type only has to supply the other methods and gets this one for free. It is the same idea as a method on a Python base class, and a type can override it, just like a subclass.
class Named:
def label(self):
return "thing"
def describe(self):
return f"{self.label()} is ready"
class Dog(Named):
def __init__(self, name):
self._name = name
def label(self):
return self._name
class Robot(Named):
def __init__(self, name):
self._name = name
def label(self):
return self._name
def describe(self):
return f"{self.label()} beeps"
for thing in [Dog("Rex"), Robot("R2")]:
print(thing.describe())trait Describe {
fn label(&self) -> String;
fn describe(&self) -> String {
format!("{} is ready", self.label())
}
}
struct Dog {
name: String,
}
impl Describe for Dog {
fn label(&self) -> String {
self.name.clone()
}
}
struct Robot {
name: String,
}
impl Describe for Robot {
fn label(&self) -> String {
self.name.clone()
}
fn describe(&self) -> String {
format!("{} beeps", self.label())
}
}
fn main() {
let dog = Dog { name: String::from("Rex") };
let robot = Robot { name: String::from("R2") };
println!("{}", dog.describe());
println!("{}", robot.describe());
}Rex is ready
R2 beepsAnything that implements Describe
A function that takes &impl Describe or T: Describe accepts any type that has
the trait. That is the Rust version of a Python type hint. Python hopes, Rust checks. The
where form says the same thing below the signature, which keeps long bounds readable.
from typing import Protocol
class Describe(Protocol):
def describe(self) -> str: ...
def show(item: Describe) -> None:
print(item.describe())
def announce(item: Describe) -> None:
print(item.describe())
def pair(a: Describe, b: Describe) -> None:
print(f"{a.describe()} and {b.describe()}")
class Dog:
def __init__(self, name):
self.name = name
def describe(self):
return f"dog {self.name}"
class Robot:
def __init__(self, name):
self.name = name
def describe(self):
return f"robot {self.name}"
show(Dog("Rex"))
announce(Robot("R2"))
pair(Dog("Rex"), Robot("R2"))trait Describe {
fn describe(&self) -> String;
}
struct Dog {
name: String,
}
impl Describe for Dog {
fn describe(&self) -> String {
format!("dog {}", self.name)
}
}
struct Robot {
name: String,
}
impl Describe for Robot {
fn describe(&self) -> String {
format!("robot {}", self.name)
}
}
fn show<T: Describe>(item: &T) {
println!("{}", item.describe());
}
fn announce(item: &impl Describe) {
println!("{}", item.describe());
}
fn pair<T, U>(a: &T, b: &U)
where
T: Describe,
U: Describe,
{
println!("{} and {}", a.describe(), b.describe());
}
fn main() {
let dog = Dog { name: String::from("Rex") };
let robot = Robot { name: String::from("R2") };
show(&dog);
announce(&robot);
pair(&dog, &robot);
}dog Rex
robot R2
dog Rex and robot R2Display, Debug and derive
{} in println! uses the Display trait, which is Python's
__str__. {:?} uses Debug, which is __repr__. You write
Display by hand; Debug, Clone and PartialEq can be generated
by #[derive(...)], as you saw in lesson 9.
import copy
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def __repr__(self):
return f"Point {{ x: {self.x}, y: {self.y} }}"
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
a = Point(1, 2)
b = copy.copy(a)
print(a)
print(repr(a))
print(str(a == b).lower())use std::fmt;
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = a.clone();
println!("{a}");
println!("{a:?}");
println!("{}", a == b);
}(1, 2)
Point { x: 1, y: 2 }
trueA list of mixed types, and the + operator
A Vec holds values of one type. To hold a mix, use Vec<Box<dyn Shape>>:
many boxes, each holding some type that implements Shape. The method is chosen at run time. In
Python you just put the objects in a list.
The last part shows a trait you have been using all along without knowing: + on your own type is
the Add trait, which is __add__.
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r * self.r
class Square:
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Point {{ x: {self.x}, y: {self.y} }}"
shapes = [Circle(1.0), Square(2.0)]
for s in shapes:
print(f"{s.area():.2f}")
p = Point(1, 2) + Point(10, 20)
print(repr(p))use std::ops::Add;
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
r: f64,
}
struct Square {
side: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.r * self.r
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.side * self.side
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point { x: self.x + other.x, y: self.y + other.y }
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { r: 1.0 }),
Box::new(Square { side: 2.0 }),
];
for s in &shapes {
println!("{:.2}", s.area());
}
let p = Point { x: 1, y: 2 } + Point { x: 10, y: 20 };
println!("{p:?}");
}3.14
4.00
Point { x: 11, y: 22 }Where the Python analogy breaks
- Duck typing is checked at compile time. A function that takes
&impl Describeonly accepts types that sayimpl Describe for .... Having a method with the right name is not enough. - Traits have methods, not fields. A default method can't read
self.name; it can only call other methods of the trait. The data lives in the struct. - Dunder methods become traits, and you opt in to each one.
__str__isDisplay,__eq__isPartialEq,__add__isAdd. Nothing is there until you implement or derive it. - A list of mixed types needs a box.
[Circle(), Square()]just works in Python. In Rust it is aVec<Box<dyn Shape>>, because aVecholds one type. - You can add your own trait to a type you didn't write, like
impl Describe for i32. That's like adding a method to Python'sint, which Python doesn't allow.
Cheat card
| Python | Rust |
|---|---|
class Dog: # duck typing | impl Describe for Dog { fn describe(&self) -> String { ... } } |
class Describe(Protocol): ... | trait Describe { fn describe(&self) -> String; } |
def show(item: Describe): | fn show(item: &impl Describe) |
def show[T: Describe](item: T): | fn show<T: Describe>(item: &T) |
class Base:
def describe(self):
return "base" | trait Describe {
fn describe(&self) -> String {
String::from("base")
}
} |
def __str__(self): ... | impl std::fmt::Display for X { fn fmt(...) -> std::fmt::Result } |
def __repr__(self): ... | #[derive(Debug)] // print with {:?} |
def __eq__(self, other): ... | #[derive(PartialEq)] // a == b |
copy.copy(x) | x.clone() // needs #[derive(Clone)] |
hasattr(x, "describe") | T: Describe // checked at compile time |
items = [Circle(), Square()] | let items: Vec<Box<dyn Shape>> = ...; |
def __add__(self, other): ... | impl std::ops::Add for X { type Output = X; ... } |