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;orf(a)moves aVecorString. The new owner takes it, andacan no longer be used. Small values like numbers,boolandcharare simply copied instead.&aborrows to read: "you may look at it". Many readers at once are fine.&mut aborrows 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.
a = [1, 2, 3]
b = a
b.append(4)
print(a)fn main() {
let a = vec![1, 2, 3];
let mut b = a;
b.push(4);
println!("{:?}", a);
}[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.
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)fn main() {
let a = vec![1, 2, 3];
let mut b = a.clone();
b.push(4);
println!("{:?}", a);
println!("{:?}", b);
}[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.
def total(numbers):
return sum(numbers)
prices = [3, 4, 5]
print(total(prices))
print(len(prices))fn total(numbers: &[i32]) -> i32 {
numbers.iter().sum()
}
fn main() {
let prices = vec![3, 4, 5];
println!("{}", total(&prices));
println!("{}", prices.len());
}12
3Letting 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.
def double_all(numbers):
for i in range(len(numbers)):
numbers[i] *= 2
values = [1, 2, 3]
double_all(values)
print(values)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);
}[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.
names = ["Ann", "Bob"]
for name in names:
if name == "Ann":
names.append("Cid")
print(names)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);
}['Ann', 'Bob', 'Cid']Where the Python analogy breaks
- Assignment moves instead of sharing.
b = ain Python gives two names for one list. In Rust,let b = a;moves theVectob, andacan't be used any more. Small values like numbers andboolare copied instead. - Passing a value to a function moves it too.
f(items)givesitemsaway for good. Pass&itemsto lend it, or&mut itemsto let the function change it. - Many readers or one writer, never both at once. Python lets any number of names change the same list. This rule is why
changing a
Vecwhile you loop over it doesn't compile. .clone()is a real copy, not a new name. For aVecofStrings it copies every string. That's fine for small data, but it isn't free like Python'sb = a.- No garbage collector. Memory is freed at the
}where its owner ends, at a point you can see in the code, not "some time later".
Cheat card
| Python | Rust |
|---|---|
b = a # same list, two names | let b = a; // moved: a is unusable now |
b = a.copy() | let b = a.clone(); |
y = x # int | let y = x; // numbers are copied |
def f(items: list[int]): ... | fn f(items: &[i32]) { } |
def f(items: list[int]): ... # changes it | fn f(items: &mut Vec<i32>) { } |
def f(name: str): ... | fn f(name: &str) { } |
f(items) # might change it | f(&items) // can only read |
f(items) # changes it | f(&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 →