Ownership, borrowing, slices

Day 2

Rust for bioinformaticians

What this lecture is

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

Stack/heap split with a Vec<u8> three-field header (ptr, len, cap) on the stack pointing to an 8-cell heap allocation holding ACGTA.

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 small diagram: a buffer of 8 cells labelled 'input' with the bytes ACGTACGT, followed by 8 more cells. A red arrow shows the strcpy writing through the buffer boundary into the adjacent region, with the labels turning red.

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 moved
println!("{:?}", 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

An SMIL-animated diagram. Step 1: `let v = vec![b'A', b'C', b'G', b'T'];` is highlighted; a stack box for v appears with its three fields (ptr, len, cap) and arrows to a heap box holding ACGT. Step 2: `let w = v;` is highlighted; a stack box for w appears beside v and the three fields copy across. Step 3: v is greyed out and crossed in red; w's arrow remains pointing at the same heap box; the data has not moved.

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 usable
println!("{} {}", q, r);   // both still valid
Two small boxes labelled q and r, both containing the byte 30 (a Phred score); the value q was copied to r and both are valid afterwards.

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 borrow

let v = vec![b'A', b'C', b'G', b'T'];
let g = gc_content(&v);          // pass &v, not v
println!("{:?}", v);             // v still owns the data

&v makes a reference; the function reads through it. v is never moved.

A stack region with three small boxes labelled v, r, s — v contains the Vec header (ptr/len/cap), r and s are both &Vec<u8> pointers. All three point at the same heap allocation holding A C G T. Both r and s have a small 'read-only' annotation; v has 'owner'.

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 &T or exactly one &mut T.

Never both. The compiler enforces this at every program point.

Many shared borrows, all at once

An SMIL-animated diagram that starts with the owner `v` and its first borrow `r1`, then animates the addition of `r2` and `r3` — three pointer arrows accumulating to the same heap region. The animation freezes on the final state showing three read-only views of the same data.

One mutable borrow, alone

Left panel labeled OK: v with one &mut v borrow, with note 'sole writer'. Right panel labeled compile error: v with both &mut v and &v, the &v crossed out and the compiler error printed below — trying to add a second borrow while a &mut is alive is rejected.

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 list
v[0].append(99)      # mutate inner list
print(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.

Two-panel before/after diagram. Left panel 'before v[0].append(99)': a stack region with two variables 'v' and 'first'; an arrow from 'v' to a heap object showing a 2-element list of pointers, the first of which goes to a heap object [1, 2], the second to [3, 4]; 'first' also points to the [1, 2] object. Right panel 'after v[0].append(99)': same layout, but the [1, 2] object is now [1, 2, 99]; both v[0] and first still point to it, so first now shows the mutated list.

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:

let mut v = vec![1u8, 2, 3];
let first = &v[0];       // shared borrow of the first element
v.push(4);               // pushes — may cause a reallocation
println!("{}", 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:

// Read-only — takes &T:
fn count_g(seq: &[u8]) -> usize { /* counts G's */ }

// Mutates in place — takes &mut T:
fn trim_in_place(buf: &mut Vec<u8>) { /* shortens buf */ }

// Consumes — takes owned T:
fn into_codons(seq: Vec<u8>) -> Vec<[u8; 3]> { /* repackages the bytes */ }
  • &[u8] — “I read your bytes; you keep them.”
  • &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

let mut v: Vec<u8> = Vec::new();           // empty, no allocation yet
v.push(b'A');                              // append
let 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:

let mut v = Vec::with_capacity(100);   // pre-allocate room for 100
v.push(b'A');                          // no growth until full
v.clear();                             // len -> 0, allocation KEPT
v.reserve(50);                         // grow only if needed

with_capacity and clear are the trick behind the revcomp-buffer exercise: allocate once, reuse forever.

Three side-by-side states of a Vec on the heap. State 1 'with_capacity(100)': stack struct shows len=0, cap=100; heap shows a 100-slot buffer all empty. State 2 'after 3 pushes': len=3, cap=100; first three heap slots filled. State 3 'after clear()': len=0, cap=100; heap buffer still allocated (slots empty but reserved).

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

Stack on the left contains v's Vec header and s's fat pointer (ptr + len = 4); heap on the right shows an 8-cell allocation owned by v with a green bracket marking the &v[2..6] range that s points into.

A slice is a pointer + length — 16 bytes, no copy.

DNA is &[u8], not &str

fn gc_content(seq: &[u8]) -> f64 {       // YES
    let mut gc = 0usize;
    for &b in seq {
        if b == b'G' || b == b'C' { gc += 1; }
    }
    gc as f64 / seq.len() as f64
}

// fn gc_content(seq: &str) -> f64 { ... }   // worse: UTF-8 tax, slow indexing

&[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]> {
    let mut out = Vec::with_capacity(seq.len() - k + 1);
    for i in 0..=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

A 7-cell row of DNA bytes ACGTACG with three coloured brackets below labelling the three k=3 sliding windows ACG, CGT, GTA, each a &[u8] view into the same backing storage.

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: &mut Vec<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

Three rows showing the same heap allocation across three states of a caller-owned Vec<u8>: filled (len 12, cap 64) from a previous call, cleared (len 0, cap 64) after clear() but same allocation, and refilled with the reverse complement (len 12, cap 64) after revcomp_into wrote into the existing storage.

The heap allocation never moves — len changes; cap and ptr stay.

Quality trim returns a slice, not a Vec

fn quality_trim(qual: &[u8], min_score: u8) -> &[u8] {
    let threshold = min_score + 33;

    let mut start = 0;
    while start < qual.len() && qual[start] < threshold {
        start += 1;
    }

    let mut end = qual.len();
    while end > start && qual[end - 1] < threshold {
        end -= 1;
    }

    &qual[start..end]
}

Zero allocation. The returned slice borrows from qual.

A 10-cell strip of Phred+33 quality bytes with cells 0-2 and 8-9 shaded grey (trimmed) and cells 3-7 shaded green (kept); two green brackets mark final positions start=3 and end=8; faded dashed arrows arc inward from the initial positions 0 and 10.

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
Top: the signature fn quality_trim(qual: &[u8], min: u8) -> &[u8] as the programmer writes it. Below: the same signature with the implicit lifetime 'a drawn in on both input and output reference, plus a dashed arrow linking input to output and the rule 'output lives no longer than the input'.

Compiler infers what you would have written by hand.

The whole rulebook on one slide

A three-row reference table with rows T (owned), &T (shared borrow), and &mut T (mutable borrow), and columns Can read?, Can mutate?, Can drop?, How many?. T can read, mutate (if mut) and drop, exactly 1 owner. &T can read only, any number. &mut T can read and mutate, exactly 1.

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.

let mut v = vec![b'A'];
let r = &v[0];
v.push(b'C');          // error: v is already borrowed by r
println!("{}", 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> {
    let mut 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.

To the exercises

In a terminal:

cd day2/ex-reverse-complement
cargo test

Four exercises today: reverse complement, buffer reuse, k-mers, quality trim. They build on each other.