Structs, enums, iterators

Day 3

Rust for bioinformaticians

What this lecture is

  • The Rust types that you spend the most time with.
  • Day 3 is where Rust starts to feel like Rust: types model the biology, the compiler keeps you honest
  • One concept per slide — what it is, why it works this way, a bioinformatics example

Concepts covered today:

  • struct and #[derive(...)]
  • impl and methods
  • enum (with and without data)
  • match and exhaustiveness
  • Option<T>
  • Result<T, E> and the ? operator
  • iterator chains
  • HashMap
  • closures

struct — a named bundle of fields

struct GenomicInterval {
    chrom: String,
    start: u64,
    end: u64,
}

let iv = GenomicInterval {
    chrom: "chr1".to_string(),
    start: 1000,
    end: 2000,
};
println!("{}-{}", iv.start, iv.end);

Field-by-field construction. Access fields with iv.start. → Book: structs

A struct in memory

What the programmer wrote

GenomicInterval {
    chrom: String  // name of
                   // the chromosome
    start: u64     // 0-based,
                   // inclusive
    end:   u64     // 0-based,
                   // exclusive
}

A named record, three fields, fixed shape.

What the machine sees

Diagram of struct GenomicInterval in memory. A blue Stack panel shows the struct as five 8-byte rows: chrom.ptr, chrom.len = 4, chrom.cap = 4 (grouped with a brace labelled String header), start = 1000, end = 2000; total 40 bytes on the stack. An orange Heap panel shows a four-cell allocation holding the bytes c, h, r, 1 with indices [0]..[3]; an arrow runs from the chrom.ptr row on the stack to the first heap cell. Footer notes that each field is laid out in place, owned strings keep their characters on the heap, and the struct itself remains a fixed-size record.

A struct is a fixed-size record; owned fields keep their heap data.

impl — methods belong to the type

Rust

impl GenomicInterval {
    fn length(&self) -> u64 {
        self.end - self.start
    }
}

&self is a read-only borrow of the value — the same borrow you saw yesterday, now used as the receiver of a method.

Python

class GenomicInterval:
    def length(self):
        return self.end - self.start

R (R6)

GenomicInterval <- R6::R6Class(
  "GenomicInterval",
  public = list(
    chrom = NULL,
    start = NULL,
    end   = NULL,
    initialize = function(c, s, e) {
      self$chrom <- c
      self$start <- s
      self$end   <- e
    },
    length = function() {
      self$end - self$start
    }
  )
)

Call site: iv.length() (Rust), iv.length() (Python), iv$length() (R).

More methods — mutation and construction

Rust

impl GenomicInterval {
    fn shift(&mut self, by: u64) {
        self.start += by;
        self.end   += by;
    }

    fn new(chrom: String,
           start: u64,
           end: u64) -> Self {
        Self { chrom, start, end }
    }
}
  • &mut self — mutable borrow; lets the method change the fields.
  • new takes no self — it’s an associated function [a function attached to the type itself, not to an instance], called as GenomicInterval::new(...).
  • Self inside the block is shorthand for “the type we’re implementing”.

Python

class GenomicInterval:
    def __init__(self, chrom, start, end):
        self.chrom = chrom
        self.start = start
        self.end   = end

    def shift(self, by):
        self.start += by
        self.end   += by

Same idea — __init__ is the constructor, ordinary methods mutate via self. The big difference: Python won’t stop you mutating from anywhere; Rust’s &mut self is checked at compile time.

Call sites: iv.shift(100), GenomicInterval::new("chr1".to_string(), 1000, 2000).

#[derive(...)] — the compiler writes the obvious code for you

#[derive(Debug, Clone, PartialEq, Eq)]
struct GenomicInterval {
    chrom: String,
    start: u64,
    end: u64,
}

The compiler writes the obvious trait implementations for you — equality, debug printing, cloning — so you don’t type them by hand.

The four you will reach for this week:

  • Debug — {:?} printing, for diagnostics
  • Clone — explicit .clone() deep copy
  • Copy — assignment copies (only if every field is also Copy)
  • PartialEq / Eq — == and !=

enum — one of a fixed set of named values

Sometimes a variable should only hold one of a fixed set of named values — like Strand::Plus and Strand::Minus.

Python — the loose way

# strings as ad-hoc tags:
strand = "+"

if strand == "+":
    score += 1
elif strand == " +":  # typo, never matches
    score += 1

Misspelling "+" as " +" is a bug your test suite may never catch. Using an int (STRAND_PLUS = 0) loses self-documentation.

Rust — Strand is a type

enum Strand { Plus, Minus }

let s = Strand::Plus;

// passing a string where Strand
// is expected:
fn step(s: Strand) { /* ... */ }
step("+");   // compile error

A Strand value is one of exactly two named variants. The compiler tracks which.

→ Book: defining an enum

Memory cost of one strand value:

  • Python strand = "+" — typically ~50 bytes (object header + interning + character storage)
  • Rust let strand = Strand::Plus; — 1 byte (enum discriminant)

A 10 million-row table of strands takes roughly ~500 MB in Python vs ~10 MB in Rust.

Enums can carry data

enum Variant {
    Snp       { pos: u64, alt: u8 },
    Insertion { pos: u64, bases: Vec<u8> },
    Deletion  { pos: u64, len: u64 },
}

Each variant carries its own fields. A Variant value is one of the three shapes — and the compiler tracks which.

Aside: in type-theory jargon this is a “sum type” or “algebraic data type” (ADT) [a value that is exactly one of several named shapes]. You’ll see those names in papers and in other languages; in this course we’ll just call them enums.

Two enum kinds, two memory layouts

Two-panel diagram. Left panel: enum Strand { Plus, Minus } shown as a single tiny tag cell with values 0 = Plus, 1 = Minus, labelled 1 byte total and fits in a register. Right panel: enum Variant { Snp{..}, Insertion{..}, Deletion{..} } shown as a small tag cell plus a payload box. The payload box contains three stacked variant rows: Snp { pos: u64, alt: u8 } at ~16 B, Insertion { pos: u64, bases: Vec<u8> } at ~32 B highlighted in orange as the largest variant, Deletion { pos: u64, len: u64 } at 16 B. A brace and annotation explain the size is tag + size of the largest variant, ~40 bytes per Variant value. Footer notes a C-style enum is a tagged integer while a sum-type enum is a tag plus a union of payloads; the compiler reads the tag to know which match arm applies.

Every enum value reserves room for its largest variant.

In plain English: every Variant value reserves room equal to its biggest case, plus 1 byte to remember which case.

match lets you read enums

fn ref_alt_delta(v: &Variant) -> i64 {
    match v {
        Variant::Snp { .. }              =>  0,
        Variant::Insertion { bases, .. } =>  bases.len() as i64,
        Variant::Deletion  { len, .. }   => -(*len as i64),
    }
}

match binds the variant’s fields by name inside the arm. The .. pattern means “ignore the rest”.

A value of an enum type enters at the top; below, three arms — one per variant — each labelled with the pattern (e.g. Strand::Plus, Strand::Minus, _); arrows show the value flowing into the first matching arm and its result coming out.

match on enum: try arms top-to-bottom; first match wins.

Exhaustiveness — the safety net

enum Strand { Plus, Minus }

match strand {
    Strand::Plus  =>  1,
    // forgot Strand::Minus
}

The compiler refuses any match that does not cover every variant:

error[E0004]: non-exhaustive patterns: `Minus` not covered
 --> src/main.rs:8:11
  |
8 |     match strand {
  |           ^^^^^^ pattern `Minus` not covered
  |
  = note: ensure that all possible cases are being handled by adding
    a match arm with a wildcard pattern, or an explicit pattern as shown

match ensures you do not forget to add needed logic

Side-by-side: left, Python if/elif chain missing one case, with a red arrow showing a silently dropped sample; right, Rust match with a compile-error diagnostic pointing at the missing variant.

A missing case is a build error, not a runtime surprise.

Option<T> — values that may be absent

enum Option<T> {
    Some(T),
    None,
}

/// Returns the position of the first G base in `seq`,
/// or `None` if there isn't one.
fn first_g(seq: &[u8]) -> Option<usize> {
    for (i, &b) in seq.iter().enumerate() {
        if b == b'G' {
            return Some(i);
        }
    }
    None
}

Option<T> replaces null. There is no other way to express absence in a typed value. The <T> is a generic parameter [a placeholder for “any type” — fill it in at the use site, e.g. Option<usize> or Option<&[u8]>].

Option in memory

Diagram titled Option<u64> — the same shape, two states, showing the enum Option<T> { Some(T), None }. Left panel headed let opt: Option<u64> = Some(42) shows a blue stack region with a small tag cell containing 1 next to a wider u64 payload cell containing 42, labelled Some and contains the value. Right panel headed let opt: Option<u64> = None shows an orange stack region with a tag cell containing 0 next to a dashed-border u64 payload cell labelled (unused, garbage), with the captions None and compiler refuses to read. A green callout at the bottom reads: Option<T> replaces null. The compiler refuses to read the value until you have checked which variant you have, followed by a match opt example.

The compiler will not let you read the payload until you check the tag.

Using Option — match, if let, helpers

match first_g(seq) {
    Some(i) => println!("first G at {i}"),
    None    => println!("no G in this read"),
}

if let Some(i) = first_g(seq) {                  // only care about Some
    println!("first G at {i}");
}

let i = first_g(seq).unwrap_or(0);               // missing G means 0
let i = first_g(seq).expect("read must contain a G");  // panic if None

→ Option docs

Result<T, E> — operations that can fail

enum Result<T, E> {
    Ok(T),
    Err(E),
}

fn parse_start(s: &str) -> Result<u64, ParseError> {
    match s.parse::<u64>() {
        Ok(n)  => Ok(n),
        Err(_) => Err(ParseError::InvalidStart),
    }
}

Result is Option’s richer sibling — failure carries a value of its own.

A function returning Result<T, E> shown with two output branches; the Ok(value) branch flows into the caller's next statement, the Err(e) branch routes to an error handler or short-circuits out.

Result has two output branches.

The ? operator is a nice shorthand

A minimal example first — one fallible call, one ?:

With ?

fn parse_count(s: &str)
    -> Result<u64, std::num::ParseIntError>
{
    let n: u64 = s.parse()?;
    Ok(n * 2)
}

? means if this is Err, return it; otherwise unwrap and continue.

Equivalent without ?

fn parse_count(s: &str)
    -> Result<u64, std::num::ParseIntError>
{
    let n: u64 = match s.parse() {
        Ok(n)  => n,
        Err(e) => return Err(e),
    };
    Ok(n * 2)
}

Four lines per fallible call, every time.

For ? to compile, the enclosing function must itself return Result (or Option).

? in a real parser — ok_or and map_err

fn parse_region(s: &str) -> Result<(String, u64, u64), ParseError> {
    let (chrom, rest)    = s.split_once(':').ok_or(ParseError::MissingColon)?;
    let (start_s, end_s) = rest.split_once('-').ok_or(ParseError::MissingDash)?;
    let start: u64 = start_s.parse().map_err(|_| ParseError::InvalidStart)?;
    let end:   u64 = end_s  .parse().map_err(|_| ParseError::InvalidEnd)?;
    Ok((chrom.to_string(), start, end))
}
  • ok_or(err) turns Option<T> into Result<T, E> — split_once returns Option, but we want ? to propagate a ParseError.
  • map_err(|_| ...) rewrites the error type — s.parse() returns the standard ParseIntError; we squeeze it into our own ParseError.

Diagram of the ? operator. A blue call box at the top reads parse_chrom(s) — returns Result<String, ParseError>. Two arrows diverge from the call: a green arrow labelled Ok(chrom) leads to a green box on the left titled unwrap and continue, showing let chrom: String = ... and the caption next line of the function runs; a red arrow labelled Err(e) leads to a red box on the right titled early return from this function, showing return Err(e); and the caption caller gets the same Err. A dashed grey caller-frame box below reads: enclosing function must itself return Result<_, E> (or Option) for ? to compile, and shows fn parse_region(s: &str) -> Result<Region, ParseError> { ... }.

Each ? is an implicit early return on Err.

Exhaustive matching keeps codon tables honest

fn translate(codon: &[u8]) -> Option<u8> {
    match codon {
        b"ATG" => Some(b'M'),
        b"TAA" | b"TAG" | b"TGA" => Some(b'*'),
        b"GCT" | b"GCC" | b"GCA" | b"GCG"
            => Some(b'A'),
        // ... 60 more arms ...
        _ => None,    // invalid / non-canonical
    }
}

64 codons. match checks you cover every byte string in your domain.

A 4x4 grid showing the standard genetic code. Rows are first base T, C, A, G; columns are second base T, C, A, G; each cell holds four sub-rows for the third base. Each row gives the codon and its one-letter amino acid. Codons are coloured by amino-acid category: hydrophobic in cream, polar uncharged in light blue, basic in light green, acidic in pink, stop codons in dark grey. The standard genetic code — 64 codons grouped by their first and second base.

The standard genetic code — 64 codons grouped by their first and second base.

Iterators — describe, don’t loop

Iterators are lazy [no work happens until something asks for an element — the chain just describes what to do]. Adaptors (map, filter, take) build a chain; consumers (collect, count, sum, for) drive it.

let gc_count = seq.iter()
    .filter(|&&b| matches!(b, b'G' | b'C'))
    .count();

let upper: Vec<u8> = seq.iter()
    .map(|&b| b.to_ascii_uppercase())
    .collect();

→ Book: iterators

Diagram titled Iterator chain: source to adaptors to consumer, with the code seq.iter().filter(|&&b| b == b'G' || b == b'C').count() across the top. On the left is a vertical column of six source cells labelled source: &[u8] containing A, C, G, T, C, A. In the middle is an orange filter stage labelled .filter(|&&b| ...) keeping only bytes that are G or C; six lines inside read A → drop, C → pass, G → pass, T → drop, C → pass, A → drop, with red drop arrows for the drops and green pass arrows for the passes connecting source to filter. On the right is a green .count() consumer pulling elements until exhausted and displaying the final value 3. Footer: Lazy: each element flows through the chain on demand; nothing happens until the consumer pulls. Compiles to the same loop you would write by hand — zero-cost abstraction.

Elements flow on demand; nothing materialises in between.

HashMap — keys to values

Rust

use std::collections::HashMap;

let mut counts: HashMap<&[u8], usize>
    = HashMap::new();
counts.insert(b"ATG", 1);
counts.insert(b"TAA", 1);

if let Some(&n) = counts.get(b"ATG") {
    println!("seen ATG {n} times");
}

The standard hash table — generic over key type and value type. Lookup is constant-time on average.

→ HashMap docs

Python (dict)

counts = {}
counts["ATG"] = 1
counts["TAA"] = 1

if "ATG" in counts:
    n = counts["ATG"]
    print(f"seen ATG {n} times")

Same data structure. Rust forces you to spell out the key and value types up front; Python infers everything at runtime.

The entry API — read-modify-write in one call

Rust — two steps, made explicit

use std::collections::HashMap;

let mut counts:
    HashMap<Vec<u8>, usize> = HashMap::new();

for window in seq.windows(k) {
    let key = window.to_vec();
    let slot = counts.entry(key).or_insert(0);
    // step 1: get a &mut to the slot
    //         (insert 0 if it wasn't there)
    *slot += 1;
    // step 2: deref the &mut and add one
}

Python — same pattern

# Python equivalent:
counts[k] = counts.get(k, 0) + 1

# or:
from collections import defaultdict
counts = defaultdict(int)
counts[k] += 1

The Rust entry API does the lookup, the maybe-insert, and the get-mut all in one — same effect as defaultdict, no extra import.

Idiomatic one-liner: *counts.entry(window.to_vec()).or_insert(0) += 1;

Diagram showing 3-mer counts in ATGATGCAT — 7 windows total; ATG appears twice. The DNA sequence ATGATGCAT is shown at the top with a bracket below noting 7 windows of length 3 slide left to right; the first window ATG is outlined in orange. Below is a bar chart of counts for the six distinct 3-mers in alphabetical order: ATG has count 2, while CAT, GAT, GCA, TGA, and TGC each have count 1.

One lookup-or-insert per window builds the histogram.

Closures can replace small functions

With capture

let threshold = 30;
let high_quality = quals.iter()
    .filter(|q| *q >= threshold)
    // captures `threshold` from outside
    .count();

|args| body. Closures capture the variables they mention from the enclosing scope.

Closure vs. named function

// closure (anonymous, one-shot):
let bump = |q: u8| q + 1;

// equivalent named function:
fn bump(q: u8) -> u8 { q + 1 }

The closure form is shorter when the function is one-line and only used here. The named-function form is what you reach for when the function needs a stable name and is called from elsewhere.

To the next lecture

Next lecture: recursion and trees — modelling a phylogeny.