Skip to main content

IndexRustTutorial

Rust Traits, Generics and Closures for JS Developers

Part 7 of Rust for web developers: traits as interfaces, default methods, generics and bounds, dyn vs impl, and closures with Fn, FnMut, FnOnce and move.

By LearnWebCraft Team24 min readBeginner

Part 7 of 15 · Rust for web developers

So far in this series we've been using three features without looking at them directly. We derived Debug and Clone, implemented Display for an error type, and imported clap's Parser. Those are traits. We used Vec<T>, Option<T> and HashMap<K, V>. Those are generics. And we've passed little functions like |a, b| b.1.cmp(&a.1) to sort_by. Those are closures.

This part covers all three properly, because they're what the rest of the series is built on. An Axum handler is a function that implements a trait. Its extractors are types implementing another trait. The router is generic over your application state. Middleware is closures and traits all the way down. When you see an Axum compile error about a trait bound not being satisfied, and you will, this part is what lets you read it.

You already know the ideas from TypeScript: interfaces, generics and arrow functions. Rust's versions line up closely enough that most of this will feel familiar, and differ in a few ways that matter. All outputs below come from Rust 1.100.0. If you're coming in fresh, part 6 left wordfreq split into a library and a binary, which we build on at the end.

Traits

Defining shared behaviour

A trait describes behaviour that types can have. Here's one for anything that can be summarised in a feed:

Fig. 1rust
trait Summary {
    fn title(&self) -> String;

    fn preview(&self) -> String {
        format!("{}...", self.title().chars().take(20).collect::<String>())
    }
}

title has no body, so every type that implements Summary must provide one. preview has a default body, which types get for free and can override. In TypeScript the closest thing is an interface, but interfaces can't carry default implementations. Rust traits sit somewhere between an interface and an abstract class.

Two types to implement it for:

Fig. 2rust
struct Post {
    title: String,
    body: String,
}

struct Comment {
    author: String,
    text: String,
}

impl Summary for Post {
    fn title(&self) -> String {
        self.title.clone()
    }
}

impl Summary for Comment {
    fn title(&self) -> String {
        format!("{} said: {}", self.author, self.text)
    }

    fn preview(&self) -> String {
        format!("comment by {}", self.author)
    }
}

Post only provides title and uses the default preview. Comment overrides both. Forget a required method and the compiler names it:

Fig. 3text
error[E0046]: not all trait items implemented, missing: `author`
  --> src/bin/e_missingitem.rs:10:1
   |
 3 |     fn author(&self) -> String;
   |     --------------------------- `author` from trait
...
10 | impl Summary for Post {
   | ^^^^^^^^^^^^^^^^^^^^^ missing `author` in implementation

The big difference from TypeScript interfaces

TypeScript interfaces are structural. Any object with a title() method returning a string satisfies an interface that asks for one, whether or not it was written with that interface in mind. Rust traits are nominal. A type only implements Summary if there's an impl Summary for ThatType block somewhere. Having a method with the right name isn't enough.

That sounds more restrictive, and in one way it is. But it buys you something TypeScript can't do: you can implement your trait for types you didn't write, and you can implement other people's traits for your types. Want every String to have a .preview()? Write impl Summary for String. Want your Post to print with {}? Implement the standard library's Display trait for it:

Fig. 4rust
use std::fmt;

impl fmt::Display for Post {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "# {}\n{}", self.title, self.body)
    }
}
Fig. 5text
# Why Rust traits feel familiar
They are interfaces with superpowers.

There's one limit, called the orphan rule: either the trait or the type must be defined in your crate. You can't implement Display for Vec<String>, because both belong to the standard library. The rule exists so two crates can't provide conflicting implementations of the same trait for the same type.

Traits you'll implement or derive all the time

The standard library's traits are how Rust types plug into the language itself:

Trait What it enables Usually
Debug {:?} formatting Derived
Display {} formatting, .to_string() Written by hand
Clone, Copy .clone(), implicit copies Derived
PartialEq, Eq == and != Derived
PartialOrd, Ord <, >, sorting Derived
Hash Use as a HashMap key Derived
Default Type::default() Derived or by hand
From, Into Conversions, and ? error conversion By hand
Iterator for loops and iterator methods By hand (part 8)
Drop Cleanup code on drop By hand, rarely

Operators are traits too. a + b calls the Add trait, a == b calls PartialEq. That's why == on two structs compares their contents: the derived PartialEq says so.

Default is particularly handy for configuration structs:

Fig. 6rustRun
#[derive(Debug, Default)]
struct Settings {
    port: u16,
    host: String,
    debug: bool,
}

let s = Settings::default();
println!("{s:?}");
let s = Settings { port: 8080, ..Default::default() };
println!("{s:?}");
Fig. 7text
Settings { port: 0, host: "", debug: false }
Settings { port: 8080, host: "", debug: false }

Combined with struct update syntax from part 4, that's the Rust version of { ...defaults, port: 8080 }.

From defines a conversion, and you get Into in the other direction automatically:

Fig. 8rust
struct Celsius(f64);
struct Fahrenheit(f64);

impl From<Celsius> for Fahrenheit {
    fn from(c: Celsius) -> Self {
        Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
    }
}

let f: Fahrenheit = Celsius(100.0).into();
let name: String = "ferris".into();
Fig. 9text
100C is 212F
ferris

"ferris".into() works because the standard library implements From<&str> for String. And you've already relied on From without knowing: in part 5, ? converted errors using exactly this trait.

Using traits: three ways to accept "anything that implements X"

Now the useful part: writing functions that work with any type implementing a trait.

impl Trait in argument position

Fig. 10rust
fn notify(item: &impl Summary) {
    println!("new: {}", item.preview());
}

notify(&post);
notify(&comment);
Fig. 11text
new: Why Rust traits feel...
new: comment by ana

&impl Summary means "a reference to some type that implements Summary". It reads well and it's the most common form for simple cases. It's the same as a TypeScript parameter typed with an interface.

Generic type parameters with trait bounds

The same function, written with an explicit type parameter:

Fig. 12rust
fn notify_generic<T: Summary>(item: &T) {
    println!("generic: {}", item.title());
}

<T: Summary> declares a type parameter T and a trait bound: T can be any type, as long as it implements Summary. In TypeScript you'd write function notify<T extends Summary>(item: T). The two forms above compile to the same thing. The explicit version is needed when you have to refer to T more than once, for instance to say that two parameters have the same type.

When the bounds get long, a where clause keeps the signature readable:

Fig. 13rust
fn headline<T>(item: &T) -> String
where
    T: Summary + fmt::Display,
{
    format!("[{}] {} chars when shown", item.title(), item.to_string().len())
}
Fig. 14text
[Why Rust traits feel familiar] 69 chars when shown

Summary + fmt::Display means T must implement both. Post does, so it's accepted. Comment doesn't implement Display, so passing it would be a compile error.

You will see where clauses everywhere in Axum's documentation. Something like where S: Clone + Send + Sync + 'static is just a list of things the type has to support. Send and Sync are about threads, and we'll meet them in part 9.

dyn Trait: a list of different types

Generics work when each call uses one concrete type. What about a list holding both posts and comments? A Vec<T> holds one type. For mixed types, you use a trait object:

Fig. 15rust
let feed: Vec<Box<dyn Summary>> = vec![Box::new(post), Box::new(comment)];
for item in &feed {
    println!("feed: {}", item.preview());
}
Fig. 16text
feed: Why Rust traits feel...
feed: comment by ana

dyn Summary means "some type that implements Summary, decided at runtime". Because different types have different sizes, a trait object has to live behind a pointer, usually Box<dyn Trait> (an owned pointer to heap memory) or &dyn Trait. Each call goes through a small lookup table to find the right method. This is how JavaScript and most object-oriented languages call methods all the time.

Static vs dynamic dispatch

The difference between impl Trait (or <T: Trait>) and dyn Trait is worth understanding, because it's a genuine choice you'll make:

Generics / impl Trait dyn Trait
Type decided At compile time At runtime
How it works The compiler makes a copy of the function for each type used (monomorphisation) One function, calls looked up through a table
Speed Calls can be inlined, fastest One indirect call per method, slightly slower
Binary size Grows with each type used Stays small
Mixed types in one collection No Yes

The default in Rust is generics, because it's zero-cost. Use dyn when you need a collection of mixed types, or when you want to choose an implementation at runtime, as we will for wordfreq below. Axum uses both: your handlers are generic and get compiled into specialised code, and the router stores them internally as boxed trait objects so different handlers can live in one routing table.

Generics

Generic functions

Here's a function that finds the largest item in any slice whose items can be compared and copied:

Fig. 17rustRun
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
    let mut best = items[0];
    for &item in items {
        if item > best {
            best = item;
        }
    }
    best
}

println!("largest i32: {}", largest(&[3, 41, 7]));
println!("largest f64: {}", largest(&[0.5, -2.0, 9.25]));
println!("largest char: {}", largest(&['r', 'u', 's', 't']));
Fig. 18text
largest i32: 41
largest f64: 9.25
largest char: u

(for &item in items is a pattern: each element of the slice is a &T, and &item destructures the reference so item is the T itself. That only works because T: Copy.)

The bounds are not optional decoration. Leave them out, and the compiler won't assume anything about T:

Fig. 19text
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> src/bin/e_nobound.rs:4:17
  |
4 |         if item > best {
  |            ---- ^ ---- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn largest<T: std::cmp::PartialOrd>(items: &[T]) -> &T {
  |             ++++++++++++++++++++++

This is a big difference from TypeScript generics. In TypeScript, a generic function body is checked loosely, and you can get away with a lot. In Rust, inside a generic function you can only do what the bounds allow. If you want to compare, you need PartialOrd. If you want to print, you need Display or Debug. If you want to clone, you need Clone. The bounds are a complete list of what the function needs from its type.

The other side of that contract shows up when a caller passes a type that doesn't meet the bounds:

Fig. 20rust
struct Price {
    cents: u64,
}

let prices = [Price { cents: 100 }, Price { cents: 250 }];
let top = largest(&prices);
Fig. 21text
error[E0277]: can't compare `Price` with `Price`
  --> src/bin/e_bound.rs:17:23
   |
17 |     let top = largest(&prices);
   |               ------- ^^^^^^^ no implementation for `Price < Price` and `Price > Price`
   |               |
   |               required by a bound introduced by this call
   |
   = help: the trait `PartialOrd` is not implemented for `Price`
note: required by a bound in `largest`
  --> src/bin/e_bound.rs:1:15
   |
 1 | fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
   |               ^^^^^^^^^^ required by this bound in `largest`
help: consider annotating `Price` with `#[derive(PartialOrd)]`

(There's a second, similar error for Copy.)

Learn to read this error. It's the most common error in Axum code, where it usually says something like "the trait Handler<_, _> is not implemented for fn item". The structure is always the same: the function you called requires some trait (here PartialOrd, "required by this bound in largest"), and the type you passed doesn't implement it. The fix is either to implement or derive the trait for your type, or to pass a different type.

Generic structs

Structs can be generic too. Here's a page of results, the kind of thing every paginated API returns:

Fig. 22rust
#[derive(Debug)]
struct Page<T> {
    items: Vec<T>,
    page: u32,
    total: usize,
}

impl<T> Page<T> {
    fn new(all: Vec<T>, page: u32, per_page: usize) -> Page<T> {
        let total = all.len();
        let items = all
            .into_iter()
            .skip((page as usize - 1) * per_page)
            .take(per_page)
            .collect();
        Page { items, page, total }
    }

    fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

impl<T: Debug> Page<T> {
    fn describe(&self) -> String {
        format!("page {} of {} items: {:?}", self.page, self.total, self.items)
    }
}
Fig. 23text
page 2 of 5 items: ["cy", "di"]
page 5 empty? true

Notice there are two impl blocks. impl<T> Page<T> applies to every Page, whatever it holds. impl<T: Debug> Page<T> adds describe only for pages whose items can be debug-printed. A Page of something without Debug simply doesn't have that method. You can't do conditional methods like that in TypeScript.

When we build the API in part 10, a generic Page<T> with #[derive(Serialize)] is exactly how we'll return paginated JSON for any resource.

Generics cost nothing at runtime

When you call largest with an i32 slice and a char slice, the compiler generates two versions of the function, one for each type, each as fast as if you'd written it by hand. That's monomorphisation. There's no boxing, no runtime type checks, and no type erasure as in TypeScript, where generics vanish completely after compilation. The cost is paid in compile time and binary size instead, which is one reason Rust builds are slower than Go's.

Closures

Anonymous functions that capture their environment

A closure is Rust's arrow function:

Fig. 24rustRun
let tax_rate = 0.2;
let with_tax = |price: f64| price * (1.0 + tax_rate);
println!("12.50 with tax: {:.2}", with_tax(12.5));

let add = |a: i32, b: i32| a + b;
println!("add: {}", add(2, 3));
Fig. 25text
12.50 with tax: 15.00
add: 5

Parameters go between pipes instead of parentheses, and the body follows. Types can usually be inferred, so |a, b| a + b is fine when the compiler can tell from usage. with_tax captures tax_rate from the surrounding scope, exactly like a JavaScript closure.

The difference is that capturing in Rust has to follow the ownership rules from part 3. A closure can capture a variable in three ways: by shared reference, by mutable reference, or by taking ownership. The compiler picks the least it needs, based on what the body does.

Fn, FnMut and FnOnce

Those three ways of capturing correspond to three traits:

Trait The closure... Can be called
Fn Only reads what it captured Any number of times, even concurrently
FnMut Changes what it captured Many times, but needs mut access
FnOnce Consumes what it captured Once

Here's an FnMut closure. It changes clicks, so it needs a mutable borrow:

Fig. 26rustRun
let mut clicks = 0;
let mut click = || clicks += 1;
click();
click();
println!("clicks: {clicks}");
Fig. 27text
clicks: 2

Notice let mut click. Calling a closure that changes its captures changes the closure itself, so the closure variable needs to be mutable. Forget it, and the compiler explains:

Fig. 28text
error[E0596]: cannot borrow `click` as mutable, as it is not declared as mutable
 --> src/bin/e_closuremut.rs:4:5
  |
3 |     let click = || clicks += 1;
  |                    ------ calling `click` requires mutable binding due to mutable borrow of `clicks`
4 |     click();
  |     ^^^^^ cannot borrow as mutable

Functions that accept closures say which kind they accept, with the same trait bounds you've just learned:

Fig. 29rustRun
fn apply_twice<F: FnMut()>(mut f: F) {
    f();
    f();
}

let mut log = Vec::new();
apply_twice(|| log.push("tick"));
println!("log: {log:?}");
Fig. 30text
log: ["tick", "tick"]

F: FnMut() accepts any closure that takes no arguments and returns nothing, including ones that change their environment. Since Fn closures can also be used where FnMut is expected, this accepts the widest range of closures that it can call twice. The general rule when writing a function that takes a closure: ask for the least powerful trait you can work with. FnOnce if you call it once, FnMut if you call it repeatedly, Fn if you need to share it.

move closures

The move keyword forces a closure to take ownership of everything it captures:

Fig. 31rustRun
let name = String::from("ferris");
let consume = move || name.len();
println!("moved name has {} bytes", consume());
Fig. 32text
moved name has 6 bytes

After this, name belongs to the closure. Why would you want that? Because a closure that borrows can't outlive the thing it borrows. This matters most when a closure runs later, somewhere else, like on another thread:

Fig. 33rust
let name = String::from("ferris");
let handle = thread::spawn(|| {
    println!("hello from a thread, {name}");
});
Fig. 34text
error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
 --> src/bin/e_thread.rs:5:32
  |
5 |     let handle = thread::spawn(|| {
  |                                ^^ may outlive borrowed value `name`
6 |         println!("hello from a thread, {name}");
  |                                         ---- `name` is borrowed here
  |
note: function requires argument type to outlive `'static`
...
help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
  |
5 |     let handle = thread::spawn(move || {
  |                                ++++

The new thread could keep running after main's name is dropped, so borrowing it isn't safe. move hands name to the thread. In JavaScript you never think about this, because the garbage collector keeps captured variables alive as long as any closure refers to them. In Rust, you decide. You'll write move a lot in async code, because spawned tasks have exactly the same problem, and in part 9 this error will look very familiar.

Returning closures

Functions can return closures, which is how you build configurable behaviour:

Fig. 35rustRun
fn make_greeter(greeting: String) -> impl Fn(&str) -> String {
    move |name| format!("{greeting}, {name}!")
}

let hello = make_greeter(String::from("Hello"));
let hola = make_greeter(String::from("Hola"));
println!("{} / {}", hello("ana"), hola("bo"));
Fig. 36text
Hello, ana! / Hola, bo!

Every closure has its own unique, unnameable type, so you can't write it in a signature. impl Fn(&str) -> String means "some type that's a closure with this signature". The move is required, because greeting is a local parameter that would otherwise be dropped when make_greeter returns.

Closures with iterator and collection methods

Closures are most often passed to methods, as you've been doing since part 1:

Fig. 37rustRun
let mut words = vec!["banana", "fig", "cherry", "kiwi"];
words.sort_by_key(|w| w.len());
println!("by length: {words:?}");

let min_len = 4;
let long: Vec<&&str> = words.iter().filter(|w| w.len() >= min_len).collect();
println!("at least {min_len}: {long:?}");
Fig. 38text
by length: ["fig", "kiwi", "banana", "cherry"]
at least 4: ["kiwi", "banana", "cherry"]

Part 8 is all about iterators, so I'll leave those there.

A taste of middleware

Here's where all three features come together, in a shape you'll recognise from every web framework. A handler is a function from a request to a response. Middleware is a function that takes a handler and returns a new handler that does something extra:

Fig. 39rustRun
struct Request {
    path: String,
}

struct Response {
    status: u16,
    body: String,
}

fn with_logging<F>(handler: F) -> impl Fn(&Request) -> Response
where
    F: Fn(&Request) -> Response,
{
    move |req| {
        let res = handler(req);
        println!("  log: {} -> {}", req.path, res.status);
        res
    }
}

let home = with_logging(|_req: &Request| Response { status: 200, body: "welcome".to_string() });
let missing = with_logging(|req: &Request| Response {
    status: 404,
    body: format!("no page at {}", req.path),
});

Calling both with a request:

Fig. 40text
  log: / -> 200
200 welcome
  log: /nope -> 404
404 no page at /nope

with_logging is generic over any handler F that implements Fn(&Request) -> Response. It returns a new closure that owns the original handler (hence move), calls it, logs, and passes the response through. If you've written Express middleware, app.use((req, res, next) => { ...; next(); }), this is the same idea with types.

Axum's middleware works on the same principle, through a trait called Service from the Tower library. It's more general, because it's async and handles errors, but when we add logging and timeouts in part 11, you'll recognise the shape.

TypeScript and Rust, side by side

TypeScript Rust
interface Summary { title(): string } trait Summary { fn title(&self) -> String; }
class Post implements Summary impl Summary for Post
Structural: any matching shape fits Nominal: needs an impl block
Abstract class with a default method Trait with a default method
Add a method to a built-in type impl MyTrait for String (orphan rule applies)
function f(x: Summary) fn f(x: &impl Summary)
function f<T extends Summary>(x: T) fn f<T: Summary>(x: &T)
T extends A & B T: A + B
Summary[] with mixed classes Vec<Box<dyn Summary>>
class Page<T> { items: T[] } struct Page<T> { items: Vec<T> }
Generics erased at runtime Generics compiled per type
toString() impl Display, then .to_string()
(a, b) => a + b |a, b| a + b
Closures capture by reference, GC keeps them alive Capture by &, &mut or by value, checked by the compiler
No equivalent move to take ownership of captures
(req) => Response callback type F: Fn(&Request) -> Response

Back to wordfreq

Let's give wordfreq a second output format. Right now it only prints a human-readable table. For a tool that other programs might call, JSON output is useful. And since we may want more formats later, this is a natural place for a trait.

A new module, src/render.rs:

Fig. 41rust
use crate::Report;
use colored::Colorize;
use std::fmt::Write;

/// Output formats the command line can choose from.
#[derive(Debug, Clone, Copy, PartialEq, clap::ValueEnum)]
pub enum Format {
    /// A readable table with bars
    Text,
    /// JSON, for other programs
    Json,
}

/// Turns a report and its top words into output.
pub trait Render {
    fn render(&self, report: &Report, top: &[(&str, usize)]) -> String;
}

pub struct TextRender;

pub struct JsonRender {
    pub pretty: bool,
}

TextRender is a unit struct, a struct with no fields. It exists only to have the trait implemented on it. JsonRender has a setting. The trait doesn't care: anything with a render method of the right shape can be a renderer.

The text version moves the printing from main into the trait, building a String with writeln!, which is println! for writing into a string instead of the terminal:

Fig. 42rust
impl Render for TextRender {
    fn render(&self, report: &Report, top: &[(&str, usize)]) -> String {
        let mut out = String::new();
        writeln!(
            out,
            "{} lines, {} words, {} unique",
            report.lines, report.words, report.unique
        )
        .unwrap();
        // ... the longest word and average lines ...
        for (rank, (word, count)) in top.iter().enumerate() {
            let bar = "#".repeat(*count);
            writeln!(out, "{:>2}. {:<10} {count:>3} {bar}", rank + 1, word.bold()).unwrap();
        }
        out
    }
}

(Writing to a String can't actually fail, but writeln! returns a Result because the same macro also writes to files and sockets, which can. The .unwrap() here is one of the "my logic guarantees success" cases from part 5.)

The JSON renderer builds the JSON by hand with format!. In real code you'd use serde_json, which we'll meet in part 10. Since our words are always lowercase letters and digits after count_words cleans them, there's nothing that needs escaping, which is the only reason hand-built JSON is safe here.

Fig. 43rust
impl Render for JsonRender {
    fn render(&self, report: &Report, top: &[(&str, usize)]) -> String {
        let (nl, pad) = if self.pretty { ("\n", "  ") } else { ("", "") };
        let words: Vec<String> = top
            .iter()
            .map(|(word, count)| format!("{{\"word\":\"{word}\",\"count\":{count}}}"))
            .collect();
        format!(
            "{{{nl}{pad}\"lines\":{},{nl}{pad}\"words\":{},{nl}{pad}\"unique\":{},{nl}{pad}\"longest\":\"{}\",{nl}{pad}\"top\":[{}]{nl}}}\n",
            report.lines,
            report.words,
            report.unique,
            report.longest,
            words.join(",")
        )
    }
}

({{ and }} in a format string print a literal brace.)

Then the function that chooses at runtime, which is where dyn earns its place:

Fig. 44rust
/// Pick a renderer at runtime.
pub fn renderer(format: Format) -> Box<dyn Render> {
    match format {
        Format::Text => Box::new(TextRender),
        Format::Json => Box::new(JsonRender { pretty: false }),
    }
}

The two arms produce different types, TextRender and JsonRender. A function can only return one type, so we box them both as Box<dyn Render>. A generic return type wouldn't work here, because the choice depends on a value only known when the program runs.

In main.rs, add a --format flag to the clap struct:

Fig. 45rust
/// Output format
#[arg(short, long, value_enum, default_value_t = Format::Text)]
format: Format,

And the end of main shrinks to three lines:

Fig. 46rust
let counts = count_words(&text);
let top = top_words(&counts, cli.top, cli.sort);
print!("{}", renderer(cli.format).render(&report, &top));

The text output is the same as before:

Fig. 47text
3 lines, 27 words, 16 unique
longest word: compiler (8 chars)
9.0 words per line

 1. is           4 ####
 2. the          4 ####
 3. cargo        3 ###

And now there's JSON:

Fig. 48bash
cargo run -q -- notes.txt -t 3 --format json
Fig. 49text
{"lines":3,"words":27,"unique":16,"longest":"compiler","top":[{"word":"is","count":4},{"word":"the","count":4},{"word":"cargo","count":3}]}

To check that it's valid JSON rather than something JSON-shaped, I piped it through Python's JSON tool, which re-printed it indented without complaint.

Two tests, one checking the exact JSON and one that runs every renderer through the same check:

Fig. 50rustRun
#[test]
fn every_renderer_mentions_the_top_word() {
    let renderers: Vec<Box<dyn Render>> = vec![renderer(Format::Text), renderer(Format::Json)];
    for r in renderers {
        assert!(r.render(&sample(), &[("b", 2)]).contains('b'));
    }
}

That second test is a nice use of trait objects: a list of different renderers, each tested through the trait. If you add a third format and forget to make it list the words, this test catches it.

Fig. 51text
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Clippy and rustfmt are both clean.

Exercises

  1. Add a --pretty flag that makes the JSON renderer use pretty: true. Where does the flag's value need to go, given that renderer only takes a Format?
  2. Add a third format, CSV, with one word,count line per word. Did the test that loops over every renderer need changing?
  3. Write a generic fn top_n<T: Ord + Clone>(items: &[T], n: usize) -> Vec<T> that returns the n largest items. Call it with numbers and with strings.
  4. Implement Display for Report so println!("{report}") prints the three summary lines. Can TextRender use it?
  5. Write fn with_timing<F: Fn(&Request) -> Response>(handler: F) -> impl Fn(&Request) -> Response that prints how long each call took, using std::time::Instant. Then wrap a handler in both with_logging and with_timing. Does the order matter?

Next up: collections and iterators

We've been using Vec and HashMap since part 1, and iterator methods like map, filter and collect without much explanation. Part 8 goes through Rust's collections properly, and then iterators, which are one of Rust's most practical features for web code. Iterator chains read like JavaScript's array methods, users.iter().filter(...).map(...).collect(), but they're lazy, they don't allocate intermediate arrays, and they compile down to the same machine code as a hand-written loop. We'll also come back to strings for a closer look, now that you know about traits and closures.