Exercise: a Box heterogeneous collection
Goal
Build a Vec<Box<dyn BioRecord>> (a vector whose elements can each be a different concrete type, all sharing the BioRecord trait) holding mixed FASTA, FASTQ, and BED records, then iterate over it and print a summary line per record.
Background
The natural-looking type Vec<dyn BioRecord> does not compile. A Vec<T> stores its elements contiguously in memory, so the compiler needs to know sizeof(T) at compile time. A trait object dyn BioRecord (gloss: a value whose concrete type is only known at run time, accessed through the trait) is unsized — a FastqRecord is bigger than a BedRecord, so dyn BioRecord has no fixed size.
The fix is to put each record behind a Box — a heap allocation with a fixed-size pointer (gloss: a single machine word) on the stack. Now every element of the vector is the same size: one Box. The actual records live on the heap, possibly of wildly different sizes.
When you call r.name() on a Box<dyn BioRecord>, Rust performs dynamic dispatch (gloss: the runtime looks up the right method via a small per-type table called a vtable, instead of baking the call into the binary at compile time). It is slightly slower than a direct call, but the cost is usually negligible compared to whatever the method itself does.
The exercise
Open the starter project:
cd day8/ex-trait-objectsYou will see a single Rust source file at src/main.rs. It already contains:
- A trait
BioRecordwith two methods:name(&self) -> &strandlength(&self) -> usize - Three structs —
FastaRecord,FastqRecord,BedRecord— each with animpl BioRecordblock whose method bodies are// TODO - A
summarizefunction that takes a&[Box<dyn BioRecord>]and returns one summary line per record (this one is provided — do not modify it) - A
mainthat builds a heterogeneousVec<Box<dyn BioRecord>>and prints the summary - A
#[cfg(test)] mod testsblock with six unit tests
Your job: fill in the six TODOs (two per struct) so all tests pass. Each one is a single-line method body.
You may not change the trait, the struct definitions, the tests, main, or summarize.
How to run
From inside day8/ex-trait-objects/:
cargo build # compile
cargo test # run the tests — these should be failing at first
cargo run # see the demo outputWhen all six tests pass, cargo test will print:
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured
and cargo run should print:
chr1 (12 bp)
read42 (8 bp)
chr1 (100 bp)
Hints
name(): return a String field as a &str
All three name() methods are one-liners that return a borrowed view of a String field on self.
fn name(&self) -> &str {
&self.name // for FastaRecord and FastqRecord
}For BedRecord the field is called chrom instead:
fn name(&self) -> &str {
&self.chrom
}The &self.<field> reborrows the String field as a &str (string slice) — Rust’s deref coercion does the String → &str conversion for you.
length() for FastaRecord and FastqRecord
For the two sequence-based records, the length is just the length of the sequence field:
fn length(&self) -> usize {
self.sequence.len()
}String::len returns a usize, which matches the trait’s return type — no cast needed.
length() for BedRecord (with a type cast)
BedRecord doesn’t carry a sequence — its length is end - start. The catch is that start and end are u64, but the trait says length returns usize. Convert with an as cast:
fn length(&self) -> usize {
(self.end - self.start) as usize
}On a 64-bit machine usize and u64 are the same width, so the cast is a no-op at runtime; the compiler just needs it to satisfy the type signature.
Solution
The full reference implementation lives in day8/ex-trait-objects-solution/src/main.rs. Try not to peek until your own version passes all six tests.
Where this leads
- Day 4 uses
noodlesheavily, andnoodlesuses traits everywhere — for readers, writers, records, indices. You will use them without thinking about them again; this exercise is the last time you have to wire one up by hand. Box<dyn Error>is the most commonBox<dyn>you will see in real Rust. It is the standard return-type trick for “this function can fail in several different ways and I do not want to enumerate them yet”:fn foo() -> Result<T, Box<dyn std::error::Error>>. The Day 4 lecture introduces it alongside the?operator.- Generic alternatives. When all elements of a collection have the same concrete type, prefer a generic
Vec<T>overVec<Box<dyn Trait>>— it is faster (no vtable lookup) and lets the compiler inline more aggressively. Reach forBox<dyn Trait>when the elements really are heterogeneous, as in this exercise.