implstd::fmt::Debugfor GenomicInterval {fn fmt(&self, f:&mutstd::fmt::Formatter<'_>) ->std::fmt::Result{// ...field-by-field formatting that the macro writes for you...}}
The {:?} formatter only works because the type implements the Debug trait. derive is a macro that writes the obvious implementation for you.
A trait is a contract a type can sign
A trait [a named bundle of methods a type can opt in to implementing — like a Java interface or a Python protocol, but checked at compile time] is declared with the trait keyword:
trait Score {fn score(&self) ->i32;}
In English: “if a type wants to call itself a Score, it must provide a method score(&self) -> i32.”
The trait does not say anything about howscore is computed. Each type that implements Score answers that question on its own terms.
Display — the human-readable face
Implementing Display gives a type a meaningful {} formatter.
Every one of these is a real trait you could implement by hand. derive writes the obvious field-by-field impl on your behalf.
How other languages do this — Python duck typing
Python doesn’t have traits. Instead, if an object happens to have a method called sequence, it can be used wherever something with .sequence() is expected — duck typing (gloss: “if it walks like a duck and quacks like a duck, it’s a duck — the language never checks”).
class FastaRecord:def sequence(self): returnself.dnaclass FastqRecord:def sequence(self): returnself.dnadef gc_content(rec): seq = rec.sequence() # no static check that rec has a sequence() methodreturnsum(b in"GC"for b in seq) /len(seq)
The function gc_content doesn’t say what types it accepts. You find out at runtime when someone passes the wrong thing in and you get an AttributeError. Rust’s trait bounds (<T: Sequence>) move that check to compile time.
How other languages do this — R S4 classes
R has two object systems. The lightweight S3 is just attributes on a list. The strict S4 system has formal class definitions and generic functions (gloss: a function whose actual implementation is picked at call time based on the argument’s class).
setClass("FastaRecord", representation(name ="character", dna ="character"))setClass("FastqRecord", representation(name ="character", dna ="character",quality ="character"))setGeneric("sequence_of", function(rec) standardGeneric("sequence_of"))setMethod("sequence_of", "FastaRecord", function(rec) rec@dna)setMethod("sequence_of", "FastqRecord", function(rec) rec@dna)
Bioconductor packages are built on S4. It looks heavyweight because it is — declarations, generics, methods, slot accessors with @. Rust traits are similar in spirit (formal interfaces, dispatch by type) but a fraction of the ceremony.
Traits Vec already implements
You have been calling these methods all week without thinking of them as trait methods.
Vec’s “syntax” is not built into the language — it is trait impls in the standard library. Any of your own types can opt in to the same syntax by implementing the same traits.
Vec is itself generic — Vec and Vec share the same methods (.push, .iter, [i]) because Vec implements the same traits regardless of its element type.
Generic functions with trait bounds
A generic function [a function written with a placeholder type, specialised by the compiler at each call site] often wants to constrain the placeholder. A trait bound [a “this placeholder must implement that trait” requirement] is the constraint:
usestd::fmt::Display;fn print_all<T:Display>(items:&[T]) {for x in items {println!("{}", x);// {} works because T: Display}}print_all(&[1,2,3]);// i32 implements Displayprint_all(&["a","b","c"]);// &str implements Display
Read <T: Display> as “for any type T that implements Display”. Inside the body you can use any method the bound guarantees — here, {} formatting.
A worked biological example — summarize over Score
trait Score {fn score(&self) ->i32;}fn summarize<T: Score>(items:&[T]) ->i32{ items.iter().map(|x| x.score()).sum()}impl Score for Strand {/* ... */}impl Score for AlignmentHit {/* ... */}impl Score for PhyloClade {/* ... */}let total = summarize(&strands);// workslet total = summarize(&alignment_hits);// workslet total = summarize(&clades);// works
One function definition. Three implementations of the trait. Each call site is a separate, fully type-checked, fully optimised specialisation.
Generics — phylogenetic trees with different tip content
A real biological generic. Recall the day-3 phylo tree, now generic over what each leaf carries:
count_tips does not look at T at all — so it works for anyT. Node<SpeciesName>, Node<Sample>, Node<GeneSymbol> — same function.
The same tree shape with different tip content: a tree of species names, a tree of sample IDs, a tree of gene symbols. The recursive structure stays the same; only the type T inside the leaves changes.
A trait method may come with a body — a default that implementing types can override or accept as-is:
trait Annotate {/// Required: a short human label.fn short(&self) ->String;/// Default: prefix the short label with "annotation: ".fn long(&self) ->String{format!("annotation: {}",self.short())}}impl Annotate for Strand {fn short(&self) ->String{matchself{ Plus =>"+", Minus =>"-"}.into() }// `long` automatically inherited.}
Iterator is the canonical example — it requires only next, and provides map, filter, sum, collect, and dozens more as default methods.
The where clause — when bounds get long
Inline bounds get crowded fast. The where clause moves them after the signature:
Functionally identical to writing fn merge<T: Display + Clone, U: Score>(...); visually much easier once there is more than one bound or more than one type parameter.
What we’ll see this afternoon
Lecture 2 picks up where this one stops.
Trait objects — Box<dyn Trait>, storing different concrete types behind one interface
Static vs dynamic dispatch — the compile-time vs runtime trade-off
Worked example — noodles readers, where a Box<dyn Read> lets you read BAM, gzipped FASTQ, or stdin behind one variable
Recap
A trait is a named bundle of methods a type can opt in to implementing — the Rust equivalent of an interface
The standard library is built on traits — Debug, Clone, Display, Iterator, Read, Write, Index, IntoIterator; every derive you have written was a trait impl
Trait bounds in generic functions (<T: Display>) let you write one function that works over many concrete types, with zero runtime cost