Traits and generics
Put the report behind an output trait with text and JSON implementations, and compare generics with trait objects by running into the limits of both.
- lesson
- 06 of 08
- read
- 13 min
A trait is a set of methods that a type promises to provide. tally already implements several from the standard library: Display, Error, From, and the derived Debug and Ord. This lesson defines one of its own, Render, with a text and a JSON implementation. Picking between the two at run time runs into the limits of both ways Rust has of calling a trait method, and those limits show what each way costs.
A report to render
Both formats should print the same data, so the first step is a struct that holds exactly what gets printed. In summary.rs, replace top_paths and top_clients with a single method that builds it:
pub struct Report<'a> {
pub requests: u64,
pub malformed: u64,
pub bytes: u64,
pub status: &'a BTreeMap<StatusClass, u64>,
pub top_paths: Vec<Count<'a>>,
pub top_clients: Vec<Count<'a>>,
} pub fn report(&self, n: usize) -> Report<'_> {
Report {
requests: self.requests,
malformed: self.malformed,
bytes: self.bytes,
status: &self.status,
top_paths: top(&self.paths, n),
top_clients: top(&self.clients, n),
}
}A Report borrows the status map and the names from the Summary it was made from, hence the lifetime.
Defining and implementing a trait
The trait and its first implementation go in a new file:
use std::io::{self, Write};
use crate::summary::Report;
pub trait Render {
fn render<W: Write>(&self, report: &Report, out: &mut W) -> io::Result<()>;
}
pub struct Text;
pub struct Json;
impl Render for Text {
fn render<W: Write>(&self, report: &Report, out: &mut W) -> io::Result<()> {
writeln!(out, "{:<10}{:>12}", "requests", report.requests)?;
writeln!(out, "{:<10}{:>12}", "malformed", report.malformed)?;
writeln!(out, "{:<10}{:>12}", "bytes", report.bytes)?;
writeln!(out, "\nstatus")?;
for (class, count) in report.status {
writeln!(out, " {:<8}{:>12}", class.label(), count)?;
}
writeln!(out, "\ntop paths")?;
for item in &report.top_paths {
writeln!(out, "{:>8} {}", item.count, item.name)?;
}
writeln!(out, "\ntop clients")?;
for item in &report.top_clients {
writeln!(out, "{:>8} {}", item.count, item.name)?;
}
Ok(())
}
}The trait declares one method and gives it no body. Text is a unit struct: it has no fields and exists to carry an implementation. writeln! is println! aimed at a writer. It returns an io::Result<()>, shorthand for Result<(), io::Error>, so each call ends in ?.
<W: Write> makes the method generic. W stands for any type that implements the standard Write trait: standard output, a file, a Vec<u8> in a test. The bound after the colon is what permits the body to write to out. The parameter could also be declared as out: &mut impl Write, which is shorthand for the same thing without naming the type.
Generic code is compiled by monomorphization. For every concrete W the program uses, the compiler generates a separate copy of render, specialized for that type. Calls are direct and can be inlined. The cost is paid in compile time and binary size, once per combination of types.
JSON with serde
The second implementation needs two crates:
cargo add serde --features derive
cargo add serde_json[dependencies]
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"serde splits serialization in two. Data types implement its Serialize trait and formats implement Serializer, so any type works with any format. serde_json is the JSON format. The derive feature adds a macro that writes the Serialize impl for a struct at compile time, so nothing is inspected at run time. Put it on Report and on Count:
use serde::Serialize;
#[derive(Serialize)]
pub struct Count<'a> {
pub name: &'a str,
pub count: u64,
}Field names become JSON keys. The status map needs string keys, and a StatusClass should appear under its label, so that type gets a hand-written impl:
use serde::{Serialize, Serializer};
impl Serialize for StatusClass {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.label())
}
}This is the kind of code the derive generates: a method that is generic over every serializer. S::Ok and S::Error are associated types, types that each Serializer implementation chooses for itself.
impl Render for Json {
fn render<W: Write>(&self, report: &Report, out: &mut W) -> io::Result<()> {
let text = serde_json::to_string_pretty(report)?;
writeln!(out, "{text}")
}
}serde_json provides a conversion from its own error type to io::Error, which is why ? is accepted here.
main.rs declares the module with mod output; and imports Json, Render and Text from it, plus std::io. The trait has to be imported along with the types: a trait’s methods can be called only where the trait is in scope. In run, a stopgap picks the format from the first argument until the next lesson brings real option parsing, and the println! calls at the end give way to a call on the chosen renderer:
let mut paths: Vec<String> = env::args().skip(1).collect();
let json = paths.first().is_some_and(|arg| arg == "--json");
if json {
paths.remove(0);
} let report = summary.report(5);
let mut out = io::stdout().lock();
if json {
Json.render(&report, &mut out)?;
} else {
Text.render(&report, &mut out)?;
}
Ok(())lock() takes exclusive hold of standard output for the rest of run, so that the many small writes do not each acquire it.
cargo run -q -- --json access.log 2>/dev/null{
"requests": 16,
"malformed": 2,
"bytes": 152631,
"status": {
"2xx": 9,
"3xx": 2,
"4xx": 3,
"5xx": 2
},
"top_paths": [
{
"name": "/",
"count": 4
},
...Choosing at run time
The if json works, and it grows with every new format. A function that returns the chosen renderer would be tidier:
pub fn renderer(json: bool) -> impl Render {
if json { Json } else { Text }
}error[E0308]: `if` and `else` have incompatible types
--> src/output.rs:45:29
|
45 | if json { Json } else { Text }
| ---- ^^^^ expected `Json`, found `Text`
| |
| expected because of this
|
help: you could change the return type to be a boxed trait object
|
44 - pub fn renderer(json: bool) -> impl Render {
44 + pub fn renderer(json: bool) -> Box<dyn Render> {
|
help: if you change the return type to expect trait objects, box the returned expressions
|
45 | if json { Box::new(Json) } else { Box::new(Text) }
| +++++++++ + +++++++++ +
For more information about this error, try `rustc --explain E0308`.In return position, impl Render means one specific type that the function chooses and the caller cannot name. It is still a single type, fixed at compile time, and the two branches produce two different ones. The compiler’s own suggestion is the way out: return a Box<dyn Render>.
dyn Render is a trait object: a value of some type that implements Render, with the choice of type deferred to run time. The compiler no longer knows its size, so it has to live behind a pointer, and Box<T> is the pointer type that owns a heap allocation. A Box<dyn Render> is two pointers wide. One points to the value and the other to a vtable, a table of that type’s implementations of the trait’s methods. Calling render looks the function up in the table.
Apply the suggestion, and there is a second error:
error[E0038]: the trait `Render` is not dyn compatible
--> src/output.rs:44:36
|
44 | pub fn renderer(json: bool) -> Box<dyn Render> {
| ^^^^^^^^^^ `Render` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> src/output.rs:6:8
|
5 | pub trait Render {
| ------ this trait is not dyn compatible...
6 | fn render<W: Write>(&self, report: &Report, out: &mut W) -> io::Result<()>;
| ^^^^^^ ...because method `render` has generic type parameters
= help: consider moving `render` to another trait
= help: the following types implement `Render`:
output::Text
output::Json
consider defining an enum where each variant holds one of these types,
implementing `Render` for this new enum and using it instead
For more information about this error, try `rustc --explain E0038`.A vtable has one slot per method. A generic method is a whole family of functions, one for each W, and no table can hold them all. The method has to give up its type parameter, and the way to keep accepting any writer is to make that a trait object as well:
pub trait Render {
fn render(&self, report: &Report, out: &mut dyn Write) -> io::Result<()>;
}Change the signatures in both impl blocks to match. The bodies stay as they are. renderer now compiles in its boxed form:
pub fn renderer(json: bool) -> Box<dyn Render> {
if json { Box::new(Json) } else { Box::new(Text) }
}main.rs imports renderer in place of the three names, and run ends like this:
let report = summary.report(5);
let mut out = io::stdout().lock();
renderer(json).render(&report, &mut out)?;
Ok(())Both formats print what they printed before.
What each one costs
The two mechanisms side by side:
Generics (<T: Trait>, impl Trait) |
Trait objects (dyn Trait) |
|
|---|---|---|
| Concrete type chosen | at compile time | at run time |
| Method call | direct, can be inlined | through the vtable |
| Machine code | one copy per concrete type | one copy |
Different types in one Vec |
no | yes |
| Limits on the trait | none | must be dyn compatible |
In tally the indirect call happens once per run, and its cost is far too small to notice. The trait object is there because the format is chosen at run time. The common default is generics, with dyn where a type has to vary at run time or where one copy of the code is preferable to many.
A trait is also not the only possible design. With two formats known in advance, an enum Format { Text, Json } and one function containing a match would do the same job with less machinery, which is what the last help line of the E0038 message hints at. The trait version keeps each format’s code in its own impl and allows a format to be added without touching a central match.
The stopgap handling of --json is now the weakest part of the program. The next lesson replaces it.
Exercises
renderaccepts any writer. Inrun, render the text report into aVec<u8>first (let mut buffer = Vec::new();), print the buffer’s length to standard error, then write the buffer to standard output. Foraccess.logthe length should be 391 bytes.- Build the enum alternative:
enum Format { Text, Json }with animpl Render for Formatthat matches onselfand callsText.renderorJson.render.renderercan then returnFormatwithout aBox. Both output formats should be unchanged. - Add a
Tsvrenderer that prints one tab-separated line per top path and per top client, such aspath<TAB>/api/orders<TAB>3andclient<TAB>203.0.113.7<TAB>7, and select it with--tsv. For the sample file it should print nine lines.