Rust for Pythonistas

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:

  • &self is a method that only reads the struct. Python's normal self.
  • &mut self is a method that changes the struct. The variable you call it on must be declared let mut.
  • No self at all is an associated function, like a @staticmethod or a second constructor. You call it with Type::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.

Python
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())
Rust
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());
}
Output
3 4
7

A 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.

Python
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)
Rust
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);
}
Output
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.

Python
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")
Rust
#[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" });
}
Output
same
different

A 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.

Python
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}")
Rust
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());
}
Output
328.1

No 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().

Python
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())
Rust
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());
}
Output
3 3
9

Where the Python analogy breaks

Cheat card

PythonRust
class Point: def __init__(self, x, y): self.x = x self.y = ystruct 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 += kfn add(&mut self, k: i32) { self.n += k; }
p = Counter() p.add(1) # changes plet mut p = Counter::new(); p.add(1);
@staticmethod @classmethodfn origin() -> Self { // no self, call with Type::origin()
self.xself.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 = vstruct Meters(f64); // read with .0
class Point: # importable from other filespub struct Point { // visible to other files

← Iterators and closures Enums and match →