Traits — the interface

Day 8, lecture 1

Rust for bioinformaticians

What this lecture is

  • Traits are Rust’s mechanism for shared interfaces — a named bundle of methods a type can opt in to implementing
  • You have been using traits since day 1 without naming them: every #[derive(Debug, Clone)] is a trait implementation written by the compiler
  • This lecture makes the mechanism explicit, then shows what you can do with it

A trait you’ve already used — #[derive(Debug)]

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

let iv = GenomicInterval { chrom: "chr1".into(), start: 100, end: 200 };
println!("{:?}", iv);    // GenomicInterval { chrom: "chr1", start: 100, end: 200 }

What derive(Debug) actually does:

impl std::fmt::Debug for GenomicInterval {
    fn fmt(&self, f: &mut std::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 how score 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.

use std::fmt;

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

impl fmt::Display for GenomicInterval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}-{}", self.chrom, self.start, self.end)
    }
}

let iv = GenomicInterval { chrom: "chr1".into(), start: 100, end: 200 };
println!("{}", iv);              // chr1:100-200
let s: String = format!("{}", iv);

You write fmt; the standard library wires it up to println!, format!, write!, to_string(), and every other {} site. Exercise 1 is exactly this.

Display vs Debug — when to use which

Display ({}) Debug ({:?})
Audience end users, logs, prose the programmer, diagnostics
Derivable? no — write by hand yes (#[derive(Debug)])
Style concise, domain-specific verbose, complete, mechanical
Example chr1:100-200 GenomicInterval { chrom: "chr1", start: 100, end: 200 }

Rule of thumb: every type should derive Debug. Implement Display only when there is a single obviously-right human-readable form.

Two structs, one trait — Sequence

A common shape: two record types from different file formats, both carrying a DNA sequence. Define a trait once, implement it twice.

trait Sequence {
    fn sequence(&self) -> &str;
}

The trait declares a single method. Any type that implements it promises to hand back a DNA sequence as a &str.

struct FastaRecord  { name: String, dna: String }
struct FastqRecord  { name: String, dna: String, quality: String }

Two record types. Same shape, different metadata.

impl Sequence for FastaRecord {
    fn sequence(&self) -> &str { &self.dna }
}
impl Sequence for FastqRecord {
    fn sequence(&self) -> &str { &self.dna }
}

Both implement Sequence by handing back &self.dna. Now any function that wants “a thing with a DNA sequence” can take &impl Sequence and accept both.

A FastaRecord box and a FastqRecord box on the left, both with an arrow pointing right at a single `fn sequence() -> &str` trait method box, which then has an arrow to the same example output 'ACGT'.

Two structs, both pointing at the same trait method.

Implementing your own trait

trait Score {
    fn score(&self) -> i32;
}

enum Strand { Plus, Minus }

impl Score for Strand {
    fn score(&self) -> i32 {
        match self {
            Strand::Plus  =>  1,
            Strand::Minus => -1,
        }
    }
}

let s = Strand::Plus;
println!("{}", s.score());     // 1

impl <Trait> for <Type> — note the for. Body must define every method the trait requires.

A trait as a contract — picture

                       ┌── impl Display for GenomicInterval
                       │
        trait Display ─┼── impl Display for Strand
                       │
                       └── impl Display for f64   (already in std)

One trait, three concrete types signing the same contract. Code that knows only “this implements Display” can use any of them — without knowing which.

Three structs on the left — GenomicInterval, Strand, f64 — each connected by an arrow to a single Display trait box in the middle, which then has arrows to three output strings on the right: 'chr1:1000-2000', 'forward', '0.42'. The same trait, three impls, three concrete outputs.

Three different types implementing the same Display trait — each produces its own formatted string when format!("{}", x) is called.

The traits that derive gives you for free

Trait What it gives you
Debug {:?} formatting for diagnostics
Clone explicit .clone() deep copy
Copy assignment copies instead of moves (every field must be Copy)
PartialEq, Eq == and !=
Hash use as a HashMap / HashSet key
Default T::default() zero-argument constructor

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): return self.dna

class FastqRecord:
    def sequence(self): return self.dna

def gc_content(rec):
    seq = rec.sequence()           # no static check that rec has a sequence() method
    return sum(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.

Trait Method it enables Code you’ve written
IntoIterator for x in vec { ... } every iteration loop
Index vec[i] every random access
Clone vec.clone() deep copies
Debug println!("{:?}", vec) diagnostics
Default Vec::default() empty constructor
PartialEq vec_a == vec_b equality

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.

Two Vec instances side by side: on the left Vec<u64> with elements [42, 100, 7]; on the right Vec<String> with elements ["chr1", "chr2", "chrX"]. Both have arrows pointing at the same method set (.iter(), .push(), [i], .len()) — implemented once on Vec<T>, available for any T.

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:

use std::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 Display
print_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);            // works
let total = summarize(&alignment_hits);     // works
let 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:

enum Node<T> {
    Leaf     { data: T, branch_length: f64 },
    Internal { branch_length: f64, children: Vec<Node<T>> },
}

fn count_tips<T>(node: &Node<T>) -> usize {
    match node {
        Node::Leaf { .. } => 1,
        Node::Internal { children, .. } => children.iter().map(count_tips).sum(),
    }
}

count_tips does not look at T at all — so it works for any T. Node<SpeciesName>, Node<Sample>, Node<GeneSymbol> — same function.

Three side-by-side small phylogenetic trees with identical topology. Left tree has tips labelled with species names (Human, Chimp, Gorilla). Middle tree has tips labelled with sample IDs (S001, S002, S003). Right tree has tips labelled with gene symbols (BRCA1, BRCA2, RAD51). All three are 'Node<T>' with T different.

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.

The same shape with a trait bound

What if we want a function that prints the tree?

use std::fmt::Display;

fn print_tree<T: Display>(node: &Node<T>, depth: usize) {
    let indent = "  ".repeat(depth);
    match node {
        Node::Leaf { data, .. } => println!("{}- {}", indent, data),
        Node::Internal { children, .. } => {
            for child in children { print_tree(child, depth + 1); }
        }
    }
}

<T: Display> is the trait bound — T must support {}. So:

  • print_tree(&node_of_string) — works (String: Display)
  • print_tree(&node_of_my_custom_type) — refused unless MyCustomType implements Display

Default methods in a trait

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 { match self { 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:

fn merge<T, U>(a: T, b: U) -> String
where
    T: Display + Clone,
    U: Score,
{
    let copy = a.clone();
    format!("{} (score {})", copy, b.score())
}

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

To the exercises

Four exercises, in order: