Dynamic Dispatch With Trait Objects

Store heterogeneous implementations behind a Box dyn trait to select behaviour at runtime, trading monomorphisation for flexibility.

RustConfig Management

Code

rustsnippet
36 lines
trait Exporter {
    fn name(&self) -> &str;
    fn export(&self, rows: &[String]) -> String;
}

struct CsvExporter;
struct JsonExporter;

impl Exporter for CsvExporter {
    fn name(&self) -> &str {
        "csv"
    }

    fn export(&self, rows: &[String]) -> String {
        rows.join("\n")
    }
}

impl Exporter for JsonExporter {
    fn name(&self) -> &str {
        "json"
    }

    fn export(&self, rows: &[String]) -> String {
        let items: Vec<String> = rows.iter().map(|r| format!("\"{r}\"")).collect();
        format!("[{}]", items.join(","))
    }
}

fn select(name: &str) -> Option<Box<dyn Exporter>> {
    match name {
        "csv" => Some(Box::new(CsvExporter)),
        "json" => Some(Box::new(JsonExporter)),
        _ => None,
    }
}

How it works

Dynamic Dispatch With Trait Objects keeps everything in the functions name, export and select.

Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Using it

The main signature reads fn name(&self) -> &str;

name is reached through its receiver type Exporter — call it on a value of that type rather than importing the name.

Key statements

let items: Vec<String> = rows.iter().map(|r| format!("\"{r}\"")).collect();
fn select(name: &str) -> Option<Box<dyn Exporter>> {
match name {
"csv" => Some(Box::new(CsvExporter)),
"json" => Some(Box::new(JsonExporter)),
_ => None,
}
}
fn export(&self, rows: &[String]) -> String {
rows.join("\n")
}

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `name`, `export`, `select` at load time.