Traits — Box and dynamic dispatch

Day 8, lecture 2

Rust for bioinformaticians

What this lecture is

This morning we wrote things like fn print_all<T: Display>(items: &[T]) — every item in the slice had to be the same type T. That works for a Vec<FastaRecord> or a Vec<f64>, but not for a list that mixes a FASTA record with a FASTQ record with a BED interval.

  • The problem: a heterogeneous (gloss: containing different types) collection
  • The Rust fix: Box<dyn Trait> — a uniform handle to “any value implementing this trait”
  • The cost: a small dynamic dispatch (gloss: looking up which function to call at runtime, instead of at compile time) overhead per call
  • When to reach for it, and when generics are still better

The problem — a heterogeneous collection

Suppose you have three concrete record types, all biological records but storing different fields:

struct FastaRecord { name: String, seq: String }
struct FastqRecord { name: String, seq: String, qual: String }
struct BedRecord   { chrom: String, start: u64, end: u64 }

You want one Vec that holds a mix of them, so you can loop over the list and ask each item the same two questions: what is your name, and how long are you?

// We wish we could write this:
let records = vec![fa, fq, bed];   // three different types — won't compile
for r in &records { println!("{} ({}bp)", r.name(), r.length()); }

Why this morning’s generic function won’t help

The function from lecture 1:

fn print_all<T: BioRecord>(items: &[T]) {
    for item in items {
        println!("{} ({}bp)", item.name(), item.length());
    }
}

For each call site, the compiler picks one concrete T. You can call print_all(&fastas) or print_all(&fastqs) — but the slice you pass in must be homogeneous. There is no T that is “FASTA or FASTQ, depending on the element”.

A common trait — the shared interface

First, define what “asking each item the same two questions” means as a trait:

trait BioRecord {
    fn name(&self) -> &str;
    fn length(&self) -> usize;
}

impl BioRecord for FastaRecord {
    fn name(&self) -> &str { &self.name }
    fn length(&self) -> usize { self.seq.len() }
}

impl BioRecord for FastqRecord {
    fn name(&self) -> &str { &self.name }
    fn length(&self) -> usize { self.seq.len() }
}

Two distinct structs, one shared interface. (We could add BedRecord the same way.)

Why Vec<dyn BioRecord> doesn’t work directly

Naive attempt:

let records: Vec<dyn BioRecord> = vec![fa, fq];
// error[E0277]: the size for values of type `dyn BioRecord` cannot
//               be known at compilation time

Vec<T> lays its elements out contiguously in memory and needs to know how big each element is. But dyn BioRecord means “any type that implements BioRecord” — and a FastaRecord (two Strings) has a different size from a FastqRecord (three Strings).

The compiler refuses: a dynamically sized type (gloss: a type whose size is not known until runtime) cannot be stored directly.

Enter Box<dyn Trait> — same size, any type behind

A Box<T> is always the same size on the stack (gloss: the small, fast region of memory each function call uses for its locals) — 8 bytes on a 64-bit machine — regardless of what T is. The actual value lives on the heap (gloss: the larger memory region the program allocates from at runtime).

So Box<dyn BioRecord> is a fixed-size handle to a heap-allocated value of some type implementing BioRecord. And Vec<Box<dyn BioRecord>> is therefore uniform — every element is the same size handle.

let records: Vec<Box<dyn BioRecord>> = vec![
    Box::new(FastaRecord { /* ... */ }),
    Box::new(FastqRecord { /* ... */ }),
];

What Box::new is doing

let fa = FastaRecord { name: "r1".into(), seq: "ACGT".into() };
let boxed: Box<dyn BioRecord> = Box::new(fa);

Three things happen in that one line:

  • fa is moved (gloss: ownership transferred — the original binding can no longer be used) onto the heap
  • Box::new returns a Box<FastaRecord> — a typed handle to the heap value
  • The assignment coerces (gloss: an automatic, type-preserving conversion the compiler inserts) Box<FastaRecord> into Box<dyn BioRecord>, attaching the vtable pointer

The concrete type FastaRecord is “forgotten” at the type level — but the runtime still knows, via the vtable.

Iterating — the magic works

Once the collection is built, iterating is ordinary:

for record in &records {
    println!("{} ({}bp)", record.name(), record.length());
}

Output:

read_001 (120bp)
read_002 (150bp)

Each record.name() call dispatches to the right implementation — FastaRecord::name for the first element, FastqRecord::name for the second — chosen at runtime based on what is actually behind the box.

A second example — counting total bases

Heterogeneous collection plus a one-line aggregation:

let total: usize = records.iter().map(|r| r.length()).sum();
println!("{} records, {} bases total", records.len(), total);

records.iter() yields &Box<dyn BioRecord>. Calling .length() on each one is a dynamic call — but to the consumer it reads like calling a method on a plain value.

Static vs dynamic dispatch — two ways to call a trait method

Static dispatch — generics

fn print_one<T: BioRecord>(x: &T) {
    println!("{}", x.name());
}
  • Compiler monomorphises (gloss: emits one specialised copy of the function per concrete T actually used)
  • Direct call, no extra indirection
  • Faster per call; larger binary

Dynamic dispatch — trait objects

fn print_one(x: &dyn BioRecord) {
    println!("{}", x.name());
}
  • One copy of the code, takes any &dyn BioRecord
  • Method call goes through a vtable lookup (next slide)
  • Slightly slower per call; smaller binary

How big is the per-call cost, really?

For most bioinformatics code: not measurable.

  • A static call compiles to a direct call instruction
  • A dynamic call compiles to a load (vtable pointer) plus an indirect call
  • The CPU’s branch predictor handles the indirect call efficiently when the same type appears repeatedly
  • The compiler cannot inline (gloss: paste the called function’s body into the caller, eliminating the call entirely) through a dyn call — this is usually the bigger lost optimisation

Rule: trait objects are fine outside the innermost loop of a hot function. Inside that loop, prefer generics.

A vtable in one paragraph

Every dyn Trait value is internally two pointers: one to the data on the heap, and one to a vtable (gloss: a small read-only table of function pointers, one entry per method of the trait, plus a destructor).

Box<dyn BioRecord>  =  ( data ptr, vtable ptr )
                              |        |
                              v        v
                          heap value   [ name(), length(), drop() ]

When you call record.length(), the generated code reads the vtable pointer, jumps to the length slot, and calls it.

Enums — a third option you already know

For a closed set of types (you know them all at compile time), an enum is often simpler than Box<dyn>:

enum Record {
    Fasta(FastaRecord),
    Fastq(FastqRecord),
}

impl Record {
    fn length(&self) -> usize {
        match self {
            Record::Fasta(r) => r.seq.len(),
            Record::Fastq(r) => r.seq.len(),
        }
    }
}

A Vec<Record> is homogeneous (every element is one Record), no heap allocation per element, no vtable lookup.

When to use Box<dyn> vs generics — rule of thumb

  • Generics (<T: Trait>) when:
    • The set of types is known at compile time
    • You want maximum speed in a hot loop
    • You only ever use one concrete type per call site
  • Box<dyn Trait> when:
    • You need a heterogeneous collection
    • You need to choose between concrete types at runtime
    • You are designing a plugin system or a config-driven pipeline
  • Don’t overthink it — both patterns are common, and you can refactor between them

A real example — noodles readers

noodles_fasta::Reader<R> is generic over its underlying source R: BufRead. Most code picks one concrete R and that is the end of the story — the compiler monomorphises and you pay nothing.

But sometimes you want one variable that can hold “any kind of byte source” — a plain file, stdin, or a gz-decompressor — without committing to one at compile time. The format depends on what the user passes on the command line.

That is the case where Box<dyn BufRead> earns its keep: a single type that can stand in for any of those sources.

Compressed or uncompressed FASTA — pick at runtime

use std::ffi::OsStr;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use flate2::read::GzDecoder;

fn open_fasta(path: &Path) -> std::io::Result<Box<dyn BufRead>> {
    let file = File::open(path)?;
    let reader: Box<dyn BufRead> = if path.extension() == Some(OsStr::new("gz")) {
        Box::new(BufReader::new(GzDecoder::new(file)))
    } else {
        Box::new(BufReader::new(file))
    };
    Ok(reader)
}

The two branches return different concrete types — BufReader<GzDecoder<File>> vs BufReader<File>. Both implement BufRead. Box<dyn BufRead> is what lets one function return either.

Returning a trait object — Box<dyn Trait> as a return type

The open_fasta pattern generalises. Any function that needs to return “one of several concrete types, all implementing Trait” must return Box<dyn Trait>:

fn pick_filter(kind: &str) -> Box<dyn Filter> {
    match kind {
        "lowercase" => Box::new(LowercaseFilter),
        "ambig"     => Box::new(AmbigFilter),
        _           => Box::new(NoopFilter),
    }
}

You cannot write -> impl Filter here — impl Trait in return position means “one specific hidden type”, but the three branches are different types.

Object safety — the gotcha

Not every trait can be turned into a dyn. A trait that uses tricks like “method returns Self” or “method has its own generic parameters” is not dyn compatible (older docs call this “not object safe”).

trait Clone { fn clone(&self) -> Self; }   // returns Self — not dyn compatible

Error you may see:

error[E0038]: the trait `Foo` cannot be made into an object

Fixes: use generics instead, or split the trait into a dyn-compatible part and a generic part.

Box<dyn Error> — the catch-all error type

A pattern you will see all over Rust code, including day 4:

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let data = std::fs::read_to_string("input.fa")?;   // io::Error
    let n: usize = data.trim().parse()?;               // ParseIntError
    println!("{}", n);
    Ok(())
}

Each ? returns a different concrete error type. Box<dyn Error> unifies them: every standard error type implements Error, so the ? operator boxes them automatically.

&dyn Trait vs Box<dyn Trait> vs Rc<dyn Trait>

Form Ownership Lives where Typical use
&dyn Trait Borrowed Borrowed from caller Function parameter, short-lived view
Box<dyn Trait> Owned Heap Heterogeneous collection, returned from function
Rc<dyn Trait> Shared (reference-counted) Heap Multiple owners (not used in this course)

All three are 2-pointer “fat pointers” — data pointer plus vtable pointer.

Bringing it home — what’s idiomatic in bioinformatics Rust

  • Most code: generic functions with trait bounds (static dispatch)
  • Box<dyn> shows up in:
    • “Open this file regardless of compression” — file readers behind a Box<dyn BufRead>
    • Plugin systems where the user picks an algorithm at runtime
    • Error types: Box<dyn std::error::Error> is the catch-all error in many tools
    • Config-driven pipelines: a Vec<Box<dyn Step>> of processing stages
  • Rarely: trait-object-heavy designs in performance-critical inner loops

Mental checklist before reaching for Box<dyn>

Ask yourself, in order:

  1. Can I just use a generic function with a trait bound? (usually yes)
  2. Is there a fixed, small set of types? Could an enum work?
  3. Do I really need different concrete types in one collection or behind one variable?
  4. If yes — is the trait dyn-compatible?
  5. Do I need ownership (Box) or is borrowing (&dyn) enough?

Most everyday Rust code answers “yes” to question 1 and stops there.

Recap

  • dyn Trait lets you forget the concrete type and program against the trait
  • Box<dyn Trait> makes the size uniform — required for Vec, struct fields, return types
  • Dynamic dispatch costs one indirect jump per call — negligible outside inner loops
  • Use generics by default; reach for Box<dyn> when types must be decided at runtime

To the last exercise

Open 04-trait-objects.qmd:

  • Build a Vec<Box<dyn BioRecord>> containing both FastaRecord and FastqRecord values
  • Write one loop that prints the name and length of each, using only the trait methods
  • Confirm with cargo test that dynamic dispatch picks the right impl for each element