Associated Types In Trait Definitions

Give a trait an associated type so each implementation chooses its own output type, then constrain that output in generic functions.

RustData Integrity

Code

rustsnippet
52 lines
use std::fmt::Display;

// Associated types in trait definitions: each implementation chooses Output
trait Summary {
    type Output;

    fn summarize(&self) -> Self::Output;
}

struct Report {
    lines: Vec<String>,
}

impl Summary for Report {
    type Output = usize;

    fn summarize(&self) -> usize {
        self.lines.len()
    }
}

struct Entry {
    title: String,
}

impl Summary for Entry {
    type Output = String;

    fn summarize(&self) -> String {
        self.title.clone()
    }
}

fn print_summary<T>(item: &T)
where
    T: Summary,
    T::Output: Display,
{
    println!("{}", item.summarize());
}

fn main() {
    let report = Report {
        lines: vec![String::from("a"), String::from("b")],
    };
    let entry = Entry {
        title: String::from("traits"),
    };

    print_summary(&report);
    print_summary(&entry);
}

What the code does

Count the functions summarize, print_summary and main as the entire surface area of Associated Types In Trait Definitions.

Applying it

The main signature reads fn summarize(&self) -> Self::Output;

Treat main as the orchestrator calling print_summary in a fixed order.

Statements that matter

fn summarize(&self) -> Self::Output;
fn summarize(&self) -> String {
self.title.clone()
}
fn summarize(&self) -> usize {
self.lines.len()
}

Interactive Tools for This Topic

FAQ

How do you run Associated Types In Trait Definitions?
Direct execution is enough; the script has no external requirements.