Rust for Pythonistas

Lesson 13 of 26

Ownership and borrowing

In Python a variable is a label on an object. Many labels can point at the same list, and a garbage collector frees the list when no label points at it any more.

Rust has no garbage collector. Instead, every value has exactly one owner. When the owner goes away (at its closing }), the value is freed. To use a value without owning it, you borrow it. For reading code, four signs are enough:

  • let b = a; or f(a) moves a Vec or String. The new owner takes it, and a can no longer be used. Small values like numbers, bool and char are simply copied instead.
  • &a borrows to read: "you may look at it". Many readers at once are fine.
  • &mut a borrows to change: "you may change it". Only one at a time, and nobody else may read meanwhile.
  • a.clone() makes a real, separate copy.

When you see & in earlier lessons, like &str, &self or for x in &v, it is this kind of borrowing.

Two names for one list vs a move

In Python, b = a gives the same list a second name, so changing b also changes a. This surprises many people. In Rust, let b = a; moves the vector: b is the new owner and a becomes unusable. The compiler stops you from using it.

Python
a = [1, 2, 3]
b = a
b.append(4)
print(a)
Rust
fn main() {
    let a = vec![1, 2, 3];
    let mut b = a;
    b.push(4);
    println!("{:?}", a);
}
Output
[1, 2, 3, 4]

Want a copy? Say .clone()

.clone() is like list.copy() or copy.deepcopy(). Copying can be expensive, so Rust makes you write it out. When reading code, every .clone() is a place where data gets copied.

Python
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)
Rust
fn main() {
    let a = vec![1, 2, 3];
    let mut b = a.clone();
    b.push(4);
    println!("{:?}", a);
    println!("{:?}", b);
}
Output
[1, 2, 3]
[1, 2, 3, 4]

Lending a value to a function: &

Passing a Vec to a function moves it into the function, and it is freed when the function ends. Usually you only want to lend it, so you put & in the parameter type and at the call. &[i32] means "a borrowed list of i32, read only". You will see it a lot in real code.

Python
def total(numbers):
    return sum(numbers)

prices = [3, 4, 5]
print(total(prices))
print(len(prices))
Rust
fn total(numbers: &[i32]) -> i32 {
    numbers.iter().sum()
}

fn main() {
    let prices = vec![3, 4, 5];
    println!("{}", total(&prices));
    println!("{}", prices.len());
}
Output
12
3

Letting a function change it: &mut

In Python, any function you pass a list to might change it, and you only know by reading the function. In Rust, the call itself tells you: &mut means "this call may change it". This is one of the most useful signs when reading Rust.

Python
def double_all(numbers):
    for i in range(len(numbers)):
        numbers[i] *= 2

values = [1, 2, 3]
double_all(values)
print(values)
Rust
fn double_all(numbers: &mut Vec<i32>) {
    for n in numbers.iter_mut() {
        *n *= 2;
    }
}

fn main() {
    let mut values = vec![1, 2, 3];
    double_all(&mut values);
    println!("{:?}", values);
}
Output
[2, 4, 6]

Readers or one writer, never both

The loop borrows names to read it. While that borrow is active, nobody may change names. Python allows changing a list while you loop over it. That is a classic source of skipped items and endless loops. Rust rejects it at compile time with error E0502. The usual fix is to collect the changes first and apply them after the loop.

Python
names = ["Ann", "Bob"]
for name in names:
    if name == "Ann":
        names.append("Cid")
print(names)
Rust
fn main() {
    let mut names = vec![String::from("Ann"), String::from("Bob")];
    for name in &names {
        if name == "Ann" {
            names.push(String::from("Cid"));
        }
    }
    println!("{:?}", names);
}
Output
['Ann', 'Bob', 'Cid']

Where the Python analogy breaks

Cheat card

PythonRust
b = a # same list, two nameslet b = a; // moved: a is unusable now
b = a.copy()let b = a.clone();
y = x # intlet y = x; // numbers are copied
def f(items: list[int]): ...fn f(items: &[i32]) { }
def f(items: list[int]): ... # changes itfn f(items: &mut Vec<i32>) { }
def f(name: str): ...fn f(name: &str) { }
f(items) # might change itf(&items) // can only read
f(items) # changes itf(&mut items) // may change
# (no equivalent: Python has no pointers)*n += 1; // change the value behind a &mut
# garbage collector frees later// freed at the owner's closing }

← Result and ? instead of exceptions Traits instead of duck typing →