The conceptual heart of Rust: who owns a value, who can read it, who can write it
Today’s tools: ownership (the rule that exactly one variable is responsible for cleaning up each value), borrowing (giving someone temporary access without handing ownership over) via &T and &mut T, slices (&[u8] — a borrowed view into a contiguous run of values), Vec<T>
Where Day 1 left off
Yesterday: a Vec<u8> is a 24-byte header on the stack pointing at a heap allocation.
A 24-byte header points at the bytes on the heap.
Today: who is allowed to touch that heap allocation, and when?
Ownership in one sentence
Every value has exactly one owner. When the owner goes out of scope, the value is dropped.
fn main() {let v =vec![b'A',b'C',b'G',b'T'];// v owns the heap allocation here.}// v goes out of scope -> heap allocation is freed automatically.
In Python you never free memory; the garbage collector does it later, on its own schedule. In C you must remember to free every allocation yourself, and forgetting causes leaks or crashes. In Rust, neither — the compiler sees where the value goes out of scope and inserts the cleanup for you, at compile time. Same effect as garbage collection, no runtime cost, no leaks.
Why ownership at all? The bug it prevents
Use-after-free in C — about 70% of all C/C++ security bugs. Rust prevents the whole class at compile time.
char* buf = malloc(1000);// char* (a pointer to bytes); malloc(1000) (ask the system for 1000 bytes)// ... use buf ...free(buf);// free(buf) (give the memory back to the system)// ... 50 lines later, someone else still has a pointer to it:buf[0]='X';// CRASH or silent corruption — that memory may// belong to a different variable by now
Another classic — buffer overrun
char input[8];strcpy(input,"ACGTACGTACGTACGT");// writes 16 bytes into 8!
The extra 8 bytes silently corrupt adjacent memory — often a function return address, which an attacker can hijack.
A 16-byte write into an 8-byte buffer spills into the next allocation; that adjacent allocation might be a function-return address.
In the wild: most browser / PDF / image-parser CVEs
In bioinformatics: genome browsers and viewers parsing untrusted BAM/VCF/GFF
In Rust: every slice access is bounds-checked — out-of-range panics cleanly instead of silently corrupting memory
Move: assignment transfers ownership
let v =vec![b'A',b'C',b'G',b'T'];let w = v;// ownership MOVES from v to w// println!("{:?}", v); // compile error: v has been movedprintln!("{:?}", w);// OK
After let w = v, v is no longer a valid name. Using it is a compile error, not a runtime crash.
What “move” actually moves
Watch the move happen: stack header copies from v to w; the heap allocation stays put; the old binding becomes invalid.
Copy types — the exception
Primitive types implement Copy. Assigning them duplicates the value instead of moving — copying one u8 is one CPU instruction, so there’s no point making you clone every integer.
let q:u8=30;let r = q;// Phred 30 — both q and r still usableprintln!("{} {}", q, r);// both still valid
Small types copy for free — both variables stay valid.
What is Copy, and what isn’t?
Rule of thumb: if it fits in a CPU register and owns no resource, it’s Copy. Otherwise, it’s move-only.
Type
Copy?
u8, i32, f64, bool, char
yes
[u8; 4] — fixed-size array of Copy items
yes
&T — a shared reference (just a pointer)
yes
Vec<T>, String, File, HashMap<K, V>
no — owns a heap allocation or OS resource
If a type owns a heap allocation, copying its header would create two owners and a double-free. So Rust moves it instead.
References — &T and &mut T
To use a value without taking ownership, borrow it via a reference.
fn gc_content(seq:&[u8]) ->f64{/* ... */}// takes a shared borrowlet v =vec![b'A',b'C',b'G',b'T'];let g = gc_content(&v);// pass &v, not vprintln!("{:?}", v);// v still owns the data
&v makes a reference; the function reads through it. v is never moved.
Two shared references (&Vec<u8>) both pointing at the same heap data — read-only views, no mutation allowed through either.
Two flavours of borrow
Form
Meaning
How many at once
&T
shared borrow — read-only view
any number
&mut T
unique borrow — read + write
exactly one
A value has either any number of &Torexactly one &mut T.
Never both. The compiler enforces this at every program point.
Many shared borrows, all at once
One mutable borrow, alone
One &mut is the only outstanding borrow — exclusive write access, no shared readers.
The same bug in Python — silent
Python doesn’t have a borrow checker. The same shape of bug compiles, runs, and gives you wrong answers:
v = [[1, 2], [3, 4]]first = v[0] # SAME object as v[0]v.append([5, 6]) # grow outer listv[0].append(99) # mutate inner listprint(first)# [1, 2, 99] — `first` silently changed
Two Python variables can quietly point at the same heap object. Mutating through one changes what the other sees — no warning. The anti-pattern has a name: aliasing.
Same trap: pandas chained-assignment (SettingWithCopyWarning), NumPy views, R reference semantics.
Python list aliasing: first and v[0] are two names for the same heap object. After v[0].append(99), both see the mutated list.
Why the borrow rules pay off — a concrete trap
This snippet would compile in C; it would silently work in Python. Rust rejects it:
letmut v =vec![1u8,2,3];let first =&v[0];// shared borrow of the first elementv.push(4);// pushes — may cause a reallocationprintln!("{}", first);// ❌ compile error: cannot borrow v as mutable// while first is alive
let first = &v[0]; — fine, valid in any language; first points at the byte 1.
v.push(4); — if v is full, this allocates a new bigger buffer, copies the bytes over, and frees the old buffer. first now points at freed memory.
In C: undefined behaviour, often silent. In Python (with mutable elements): silent aliasing, wrong answer downstream. In Rust: compile error before you even run the program.
The previous slide showed the Python version of this same trap. Below is the Rust version — note the compiler refuses to build.
Borrowing in function signatures
Three concrete shapes, one for each ownership story:
&mut Vec<u8> — “I write into your buffer; you keep the allocation.”
Vec<u8> — “Hand it over; I own it now.”
Default to &T; use &mut T only to mutate; take ownership only to consume.
Vec<T> — owned, growable heap buffer
letmut v:Vec<u8>=Vec::new();// empty, no allocation yetv.push(b'A');// appendlet n = v.len();// current length
Vec<T>owns its heap buffer. Returning it from a function transfers that ownership.
Capacity control — for hot loops
When you know the rough size ahead of time, three more methods avoid reallocation:
letmut v =Vec::with_capacity(100);// pre-allocate room for 100v.push(b'A');// no growth until fullv.clear();// len -> 0, allocation KEPTv.reserve(50);// grow only if needed
with_capacity and clear are the trick behind the revcomp-buffer exercise: allocate once, reuse forever.
A Vec keeps len (current items) and cap (room reserved); clear() sets len = 0 but the heap buffer stays allocated for reuse.
Slices — &[T], a view into someone’s buffer
let v =vec![b'A',b'C',b'G',b'T',b'A',b'C',b'G',b'T'];let s:&[u8] =&v[2..6];// view of indices 2, 3, 4, 5 (length 4)println!("{}", s.len());// 4
A slice is a pointer + length. No allocation. It borrows from the source.
While s exists, v cannot be moved, dropped, or mutated.
A slice = pointer + length
A slice is two fields — a pointer to the first element, and a length. 16 bytes on a 64-bit machine, no copy. (The informal name is “fat pointer” — a pointer that carries extra metadata alongside the address.)
A slice is a pointer + length — 16 bytes, no copy.
&[u8] is just bytes — fast indexing (covered Day 9), drops straight into byte-literal patterns.
Range expressions for slicing
&seq[..] // the whole thing&seq[..3] // first 3-mer (prefix)&seq[seq.len()-3..] // last 3-mer (suffix)&seq[a..b] // a (inclusive) to b (exclusive)&seq[a..=b] // a to b inclusive
Out-of-bounds slicing panics at runtime:
let seq =b"ACGT";let bad =&seq[2..10];// panics: "byte index 10 out of bounds"
k-mers as slice views
fn kmers(seq:&[u8], k:usize) ->Vec<&[u8]>{letmut out =Vec::with_capacity(seq.len() - k +1);for i in0..=seq.len() - k { out.push(&seq[i..i + k]);// a view, not a copy} out}
For a 100 Mb genome with k=21: ~100M slices (16 bytes each), zero bytes of DNA duplicated.
k-mers — picture
Every k-mer is a view into the same buffer — no copies.
Writing into a caller-owned buffer
A function that allocates a fresh Vec on every call is wasteful in a hot loop. Allocation has a real cost — every Vec::new() or String::from(...) goes through the system allocator, takes ~100-500 ns, and competes with every other thread doing the same.
fn reverse_complement_into(seq:&[u8], out:&mutVec<u8>) { out.clear();// len = 0, allocation KEPT out.reserve(seq.len());for i in (0..seq.len()).rev() { out.push(complement_base(seq[i]));}}
The same heap allocation is reused across millions of calls. One allocation instead of a million.
Buffer reuse — picture
The heap allocation never moves — len changes; cap and ptr stay.
Zero allocation. The returned slice borrows from qual.
Both pointers walk inward; the slice between them is what we keep.
Lifetime elision
Elision = “leaving something out that the compiler can figure out for you.”
The rule: one reference in, one reference out ⇒ the output borrows from the input.
fn quality_trim(qual:&[u8], min:u8) ->&[u8] {/* ... */}// ^^^^^ ^^^^^// output borrows from qual; can't outlive it
Compiler infers what you would have written by hand.
The whole rulebook on one slide
Any number of readers, or exactly one writer — never both.
What you can Copy, and what you must move
Type
On assignment
u8, i32, usize, f64, bool, char
copied (Copy)
[u8; 4] and other fixed arrays of Copy types
copied
References &T, &mut T (the pointer itself)
copied
Vec<u8>, String, File, HashMap<K, V>
moved
If in doubt: anything that owns a heap allocation is move-only.
Common borrow-checker errors (1/2)
E0382 — borrow of moved value. You used v after handing it away.
let v =vec![b'A',b'C'];let w = v;println!("{:?}", v);// error: v was moved into w
Fix: pass &v (borrow) instead of v, or do the print first.
E0502 — cannot borrow as mutable / immutable. A & and a &mut overlap.
letmut v =vec![b'A'];let r =&v[0];v.push(b'C');// error: v is already borrowed by rprintln!("{}", r);
Fix: narrow the scope of r, or copy the byte (let r = v[0];).
Common borrow-checker errors (2/2)
E0507 — cannot move out of borrowed content. You tried to take ownership from behind a &T.
fn first(v:&Vec<u8>) ->Vec<u8>{*v }// error: can't move out of &
Fix:v.clone(), or change the API to take Vec<u8> by value.
The error messages are good — they almost always include a suggested fix at the bottom. Read them.
A function that returns ownership
fn reverse_complement(seq:&[u8]) ->Vec<u8>{letmut out =Vec::with_capacity(seq.len());for i in (0..seq.len()).rev() { out.push(complement_base(seq[i]));} out // ownership of the Vec MOVES to the caller}
Caller receives a fresh Vec<u8> they own. Function keeps nothing.
Recap
Every value has one owner; out of scope ⇒ dropped (no GC).
Assignment moves by default; primitives are Copy.
&T — shared, many readers, no writers.
&mut T — unique, sole writer, no other borrows.
Slices &[u8] are fat pointers (ptr + len); zero allocation.
Vec<u8> owns its heap buffer; clear() keeps the allocation.
Lifetime elision: one-in, one-out reference signatures need no annotation.