Lesson 9 of 26
Structs and impl
A Python class keeps data and behaviour in one place. Rust splits it in two: the data is a
struct, and the functions on it live in an impl block. Read them as one thing:
"here is what a point is, and here is what you can do with it".
The first argument of a function inside impl tells you which kind it is:
&selfis a method that only reads the struct. Python's normalself.&mut selfis a method that changes the struct. The variable you call it on must be declaredlet mut.- No
selfat all is an associated function, like a@staticmethodor a second constructor. You call it withType::name().
Fields are read with a dot, the same as Python: p.x. There is no inheritance in Rust. Shared
behaviour comes from traits, in lesson 14.
A dataclass becomes a struct and an impl
A dataclass gives you __init__, field access and methods for free. In Rust you write the
fields once, then a plain function called new that builds one. Hover the marked lines.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def total(self):
return self.x + self.y
p = Point(3, 4)
print(p.x, p.y)
print(p.total())struct Point {
x: i32,
y: i32,
}
impl Point {
fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
fn total(&self) -> i32 {
self.x + self.y
}
}
fn main() {
let p = Point::new(3, 4);
println!("{} {}", p.x, p.y);
println!("{}", p.total());
}3 4
7A method that changes the struct needs &mut self
&mut self is the "this method writes to the struct" marker. You will see it in most real
code, and it has a second effect: the variable you call it on must also be mut.
class Counter:
def __init__(self):
self.n = 0
def add(self, k):
self.n += k
c = Counter()
c.add(2)
c.add(5)
print(c.n)struct Counter {
n: i32,
}
impl Counter {
fn new() -> Self {
Counter { n: 0 }
}
fn add(&mut self, k: i32) {
self.n += k;
}
}
fn main() {
let mut c = Counter::new();
c.add(2);
c.add(5);
println!("{}", c.n);
}7#[derive] gives == and copying
A dataclass writes __eq__ and __repr__ for you. In Rust you ask for that behaviour
with #[derive(...)] above the struct. Each name in the list adds one thing, and nothing else about the
struct changes. Without the derive, == on two structs does not compile.
from dataclasses import dataclass
import copy
@dataclass
class Tag:
name: str
count: int
a = Tag("hot", 2)
b = copy.copy(a)
print("same" if a == b else "different")
c = Tag("cold", 5)
print("same" if a == c else "different")#[derive(Debug, Clone, PartialEq)]
struct Tag {
name: String,
count: i32,
}
fn main() {
let a = Tag { name: String::from("hot"), count: 2 };
let b = a.clone();
println!("{}", if a == b { "same" } else { "different" });
let c = Tag { name: String::from("cold"), count: 5 };
println!("{}", if a == c { "same" } else { "different" });
}same
differentA tuple struct holds one unnamed field
When a type is just one value with a name, Rust often uses a tuple struct: a one-line replacement
for a class with a single attribute. The field has no name, so you read it with .0.
class Meters:
def __init__(self, value):
self.value = value
def to_feet(self):
return self.value * 3.281
d = Meters(100)
print(f"{d.to_feet():.1f}")struct Meters(f64);
impl Meters {
fn to_feet(&self) -> f64 {
self.0 * 3.281
}
}
fn main() {
let d = Meters(100.0);
println!("{:.1}", d.to_feet());
}328.1No self: an associated function
A function in an impl block with no self belongs to the type, not to a value. It is
how Rust writes a @classmethod or a second constructor. You call it with Type::name().
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@classmethod
def square(cls, size):
return cls(size, size)
def area(self):
return self.width * self.height
r = Rectangle.square(3)
print(r.width, r.height)
print(r.area())struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn square(size: u32) -> Self {
Rectangle { width: size, height: size }
}
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let r = Rectangle::square(3);
println!("{} {}", r.width, r.height);
println!("{}", r.area());
}3 3
9Where the Python analogy breaks
- No inheritance. A struct can't extend another struct. Share behavior with traits (lesson 14), or put one struct inside another as a field.
- No new fields at run time.
p.color = "red"doesn't compile unlesscoloris declared in the struct. Every field is listed up front, with its type. newis a normal function, not a special method like__init__. You can skip it and writePoint { x: 1, y: 2 }, or have several constructors with different names.selfsays how a method uses the value:&selfreads it,&mut selfchanges it, and plainselftakes it over. Python'sselfis always the same.- Nothing comes for free. A dataclass gets
__repr__and__eq__automatically. A struct gets them only when you add#[derive(Debug, PartialEq)].
Cheat card
| Python | Rust |
|---|---|
class Point:
def __init__(self, x, y):
self.x = x
self.y = y | struct Point {
x: i32,
y: i32,
} |
p = Point(1, 2) | let p = Point::new(1, 2); |
def total(self): | fn total(&self) -> i32 { |
def add(self, k):
self.n += k | fn add(&mut self, k: i32) {
self.n += k;
} |
p = Counter()
p.add(1) # changes p | let mut p = Counter::new();
p.add(1); |
@staticmethod
@classmethod | fn origin() -> Self { // no self, call with Type::origin() |
self.x | self.x |
print(repr(p)) | #[derive(Debug)] + println!("{:?}", p); |
a == b | #[derive(PartialEq)] + a == b |
copy.copy(p) | p.clone() // needs #[derive(Clone)] |
class Meters:
self.value = v | struct Meters(f64); // read with .0 |
class Point: # importable from other files | pub struct Point { // visible to other files |