Skip to main content

Programming languages · Advanced · 25 min

Share behaviour in Rust with traits and generics

By Padding · Updated 18 Nov 2026
Debian 13 (rust:1.100 image) · Rust 1.100.0 · Cargo 1.100.0

You will build a small Rust 1.100 library of courier shipping-cost rules that share one trait, use it through generic functions, impl Trait and Box<dyn Trait>, and finish knowing when to pick generics and when to pick trait objects.

On this page

A trait in Rust names a set of methods that several types promise to provide. Generic code is then written once against the trait, not against each type. Rust gives you two ways to use that shared behaviour. Generics are resolved at compile time: the compiler writes a separate copy of the function for each concrete type it is called with. Trait objects (dyn Trait) are resolved at run time: one copy of the code looks up the right method through a table of function pointers. Both are correct tools, and much of writing good Rust is knowing which one a piece of code needs.

You will build a small library of shipping-cost rules for couriers. A flat-rate courier charges the same for every parcel, a per-kilo courier charges by weight, and a zoned courier charges less inside its home city. Each one is its own struct, and all of them implement one ShippingRule trait. On the way you derive Debug, Clone and PartialEq, write generic functions with trait bounds and where clauses, use impl Trait in both positions, put mixed couriers in a Vec<Box<dyn ShippingRule>>, and implement Display and From for your own types.

Prices are stored as whole numbers in the currency's minor unit (cents, pence, kobo), never as floats, so 4_500 means 45.00. That is how payment systems store money, and it keeps every sum exact. The project has no dependencies, so Cargo downloads nothing from crates.io; after Rust itself is installed, the whole tutorial works offline, which helps on a metered or prepaid connection.

The code lives in one Cargo package: a library in src/lib.rs that grows step by step, and a src/main.rs you replace at each step to try the new part.

Step 1 · Create the package and a Parcel type

Create the package in a throwaway folder:

Bash
cargo new ~/shipping-demo
cd ~/shipping-demo

Write the first part of the library. A Parcel has a weight in grams and a destination city. The derive line asks the compiler to write three trait implementations for you: Debug (print the value with {:?}), Clone (make a deep copy with .clone()) and PartialEq (compare two parcels with ==, field by field):

Bash
cat > src/lib.rs <<'RS'
#[derive(Debug, Clone, PartialEq)]
pub struct Parcel {
    pub weight_g: u32,
    pub destination: String,
}

impl Parcel {
    pub fn new(weight_g: u32, destination: &str) -> Self {
        Parcel {
            weight_g,
            destination: destination.to_string(),
        }
    }
}
RS

Cargo sees both src/lib.rs and src/main.rs, so the package now has a library crate called shipping_demo (the hyphen becomes an underscore) and a program that can use it. Replace src/main.rs:

Bash
cat > src/main.rs <<'RS'
use shipping_demo::Parcel;

fn main() {
    let shoes = Parcel::new(1_200, "Lagos");
    let copy = shoes.clone();
    println!("{shoes:?}");
    println!("same parcel: {}", shoes == copy);

    let heavier = Parcel { weight_g: 3_000, ..copy };
    println!("{heavier:?}");
    println!("same parcel: {}", shoes == heavier);
}
RS
cargo run -q

Parcel cannot derive Copy, because it holds a String, which owns heap memory. That is why copy needs an explicit .clone(), and why ..copy (take the remaining fields from copy) moves copy's string into heavier.

Check it worked

The program prints four lines:

Text
Parcel { weight_g: 1200, destination: "Lagos" }
same parcel: true
Parcel { weight_g: 3000, destination: "Lagos" }
same parcel: false

Step 2 · Define a trait with a default method

Append the trait and two couriers to the library. ShippingRule has two required methods, name and cost, and one default method, quote, whose body is written in the trait itself. Every type that implements the trait gets quote for free and may replace it:

Bash
cat >> src/lib.rs <<'RS'

pub trait ShippingRule {
    fn name(&self) -> &str;

    /// Cost in the currency's minor unit (cents, pence, kobo).
    fn cost(&self, parcel: &Parcel) -> u64;

    fn quote(&self, parcel: &Parcel) -> String {
        format!(
            "{}: {} for {} g to {}",
            self.name(),
            self.cost(parcel),
            parcel.weight_g,
            parcel.destination
        )
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct FlatRate {
    pub price: u64,
}

impl ShippingRule for FlatRate {
    fn name(&self) -> &str {
        "Flat rate"
    }

    fn cost(&self, _parcel: &Parcel) -> u64 {
        self.price
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct PerKilo {
    pub base: u64,
    pub per_kg: u64,
}

impl ShippingRule for PerKilo {
    fn name(&self) -> &str {
        "Per kilo"
    }

    fn cost(&self, parcel: &Parcel) -> u64 {
        let kilos = u64::from(parcel.weight_g.div_ceil(1000));
        self.base + self.per_kg * kilos
    }

    fn quote(&self, parcel: &Parcel) -> String {
        let kilos = parcel.weight_g.div_ceil(1000);
        format!(
            "{}: {} ({} kg charged) to {}",
            self.name(),
            self.cost(parcel),
            kilos,
            parcel.destination
        )
    }
}
RS

FlatRate keeps the default quote. PerKilo overrides it to say how many kilos it charged for: div_ceil rounds 2,300 g up to 3 kg, as most couriers do. Inside the default method, self.name() and self.cost(parcel) call whichever implementation the concrete type provides.

Replace src/main.rs to quote one parcel with both couriers:

Bash
cat > src/main.rs <<'RS'
use shipping_demo::{FlatRate, Parcel, PerKilo, ShippingRule};

fn main() {
    let parcel = Parcel::new(2_300, "Abuja");
    let flat = FlatRate { price: 4_500 };
    let per_kilo = PerKilo { base: 1_000, per_kg: 1_200 };
    println!("{}", flat.quote(&parcel));
    println!("{}", per_kilo.quote(&parcel));
}
RS
cargo run -q

The use line imports ShippingRule as well as the structs. Trait methods can only be called when the trait is in scope; leave it out and the compiler says quote is not found and suggests the import.

Check it worked

The output is Flat rate: 4500 for 2300 g to Abuja followed by Per kilo: 4600 (3 kg charged) to Abuja. The first line comes from the default method, the second from the override.

Step 3 · Write generic functions with trait bounds and where clauses

Append two generic functions. cheapest takes a slice of any one type R that implements ShippingRule and returns the rule with the lowest cost. compare takes two rules that may be different types; its bounds are long, so they go in a where clause after the signature, which reads better than packing them between the angle brackets:

Bash
cat >> src/lib.rs <<'RS'

pub fn cheapest<'a, R: ShippingRule>(rules: &'a [R], parcel: &Parcel) -> Option<&'a R> {
    rules.iter().min_by_key(|rule| rule.cost(parcel))
}

pub fn compare<A, B>(a: &A, b: &B, parcel: &Parcel) -> String
where
    A: ShippingRule + std::fmt::Debug,
    B: ShippingRule + std::fmt::Debug,
{
    let (cost_a, cost_b) = (a.cost(parcel), b.cost(parcel));
    if cost_a <= cost_b {
        format!("{a:?} wins by {}", cost_b - cost_a)
    } else {
        format!("{b:?} wins by {}", cost_a - cost_b)
    }
}
RS

The bound R: ShippingRule is what lets the body call rule.cost. The lifetime 'a tells the compiler that the returned reference points into rules, not into parcel; with two borrowed arguments it cannot guess, and leaving 'a out fails with error[E0106]: missing lifetime specifier. compare needs Debug as well, because it prints the winner with {:?}; without that bound the body would not compile, even though both of today's couriers derive Debug. The bounds are a contract: callers must meet them, and the body may use only what they promise.

Replace src/main.rs:

Bash
cat > src/main.rs <<'RS'
use shipping_demo::{cheapest, compare, FlatRate, Parcel, PerKilo, ShippingRule};

fn main() {
    let small = Parcel::new(800, "Accra");
    let big = Parcel::new(6_500, "Accra");
    let flat = FlatRate { price: 4_500 };
    let per_kilo = PerKilo { base: 1_000, per_kg: 1_200 };
    println!("{}", compare(&flat, &per_kilo, &small));
    println!("{}", compare(&flat, &per_kilo, &big));

    let offers = [
        PerKilo { base: 1_000, per_kg: 1_200 },
        PerKilo { base: 2_500, per_kg: 600 },
    ];
    if let Some(best) = cheapest(&offers, &big) {
        println!("cheapest per-kilo offer: {best:?} at {}", best.cost(&big));
    }
}
RS
cargo run -q

cheapest works on offers because every element is a PerKilo. An array holding a FlatRate and a PerKilo together would not even type-check: arrays and slices hold one type, and R stands for exactly one type per call. You will fix that with trait objects later.

Now see a bound reject a caller. Create an example program that passes a plain String as a courier:

Bash
mkdir -p examples
cat > examples/not_a_rule.rs <<'RS'
use shipping_demo::{compare, FlatRate, Parcel};

fn main() {
    let parcel = Parcel::new(800, "Accra");
    let post_office = String::from("Post office");
    println!("{}", compare(&post_office, &FlatRate { price: 4_500 }, &parcel));
}
RS
Bash
cargo build --example not_a_rule

The build fails with error[E0277], saying that String does not implement ShippingRule, and points at the bound in compare that required it. The check happens at the call site, before any code runs. Delete the example so it does not get in the way:

Bash
rm examples/not_a_rule.rs

Check it worked

cargo run -q prints three lines:

Text
PerKilo { base: 1000, per_kg: 1200 } wins by 2300
FlatRate { price: 4500 } wins by 4900
cheapest per-kilo offer: PerKilo { base: 2500, per_kg: 600 } at 6700

The per-kilo courier wins the 800 g parcel (22.00 against 45.00), the flat rate wins the 6.5 kg one, and the second per-kilo offer is the cheaper of the two for heavy parcels.

Step 4 · Use impl Trait in argument and return position

impl Trait is shorter syntax for two different ideas, depending on where it appears. Append three functions:

Bash
cat >> src/lib.rs <<'RS'

pub fn print_quote(rule: &impl ShippingRule, parcel: &Parcel) {
    println!("{}", rule.quote(parcel));
}

pub fn weekend_rate(weekday: &PerKilo) -> impl ShippingRule + use<> {
    PerKilo {
        base: weekday.base + 500,
        per_kg: weekday.per_kg,
    }
}

pub fn costs<R: ShippingRule>(rules: &[R], parcel: &Parcel) -> impl Iterator<Item = u64> {
    rules.iter().map(move |rule| rule.cost(parcel))
}
RS

In argument position, rule: &impl ShippingRule means exactly what <R: ShippingRule>(rule: &R) means: the caller picks the type and the compiler makes a copy of print_quote for it. Use it when the type parameter appears once and you do not need to name it.

In return position, -> impl ShippingRule means the function picks one concrete type and the caller only learns that it implements ShippingRule. weekend_rate returns a PerKilo, but callers cannot rely on that: they can call name, cost and quote, and nothing else. You can change the struct later without breaking them. costs shows the most common use: iterator and closure types are long or cannot be written at all, and impl Iterator<Item = u64> hides them. Under the Rust 2024 edition (the default for cargo new since Rust 1.85) a returned impl Trait captures every lifetime in scope, so the iterator from costs borrows from rules and parcel without any lifetime annotations. That same rule would make weekend_rate's result look as if it still borrowed weekday, and main below, which moves weekday into an array afterwards, would fail with error[E0505]. The + use<> on weekend_rate is a precise-capturing bound: the empty list says the returned value borrows nothing, which is true, because it is a fresh PerKilo.

Replace src/main.rs:

Bash
cat > src/main.rs <<'RS'
use shipping_demo::{costs, print_quote, weekend_rate, FlatRate, Parcel, PerKilo};

fn main() {
    let parcel = Parcel::new(2_300, "Nairobi");
    let weekday = PerKilo { base: 1_000, per_kg: 1_200 };

    print_quote(&FlatRate { price: 4_500 }, &parcel);
    let weekend = weekend_rate(&weekday);
    print_quote(&weekend, &parcel);

    let offers = [weekday, PerKilo { base: 2_500, per_kg: 600 }];
    let all: Vec<u64> = costs(&offers, &parcel).collect();
    println!("costs: {all:?}");
}
RS
cargo run -q

Return-position impl Trait has a firm limit: every path through the function must return the same concrete type. Try returning a different courier depending on the destination:

Bash
cat > examples/two_types.rs <<'RS'
use shipping_demo::{FlatRate, PerKilo, ShippingRule};

fn courier_for(destination: &str) -> impl ShippingRule {
    if destination == "Lagos" {
        FlatRate { price: 3_000 }
    } else {
        PerKilo { base: 1_000, per_kg: 1_200 }
    }
}

fn main() {
    println!("{}", courier_for("Kano").name());
}
RS
Bash
cargo build --example two_types

The build fails with error[E0308], something like "if and else have incompatible types": the compiler expected FlatRate from the else branch because the if branch set the hidden type. The help text may suggest boxing the values. That suggestion is the next step. Delete the example:

Bash
rm examples/two_types.rs

Check it worked

cargo run -q prints:

Text
Flat rate: 4500 for 2300 g to Nairobi
Per kilo: 5100 (3 kg charged) to Nairobi
costs: [4600, 4300]

The second line comes from the opaque weekend rate, and its override of quote still runs: hiding the type does not change which code is called.

Step 5 · Put mixed couriers in a Vec of trait objects

Add the third courier. A Zoned rule charges one price inside its home city and another everywhere else:

Bash
cat >> src/lib.rs <<'RS'

#[derive(Debug, Clone, PartialEq)]
pub struct Zoned {
    pub home_city: String,
    pub local: u64,
    pub national: u64,
}

impl ShippingRule for Zoned {
    fn name(&self) -> &str {
        "Zoned"
    }

    fn cost(&self, parcel: &Parcel) -> u64 {
        if parcel.destination == self.home_city {
            self.local
        } else {
            self.national
        }
    }
}
RS

To keep three different types in one list, store each behind a pointer and erase its concrete type: Box<dyn ShippingRule> is a heap-allocated value of some type that implements ShippingRule. Replace src/main.rs:

Bash
cat > src/main.rs <<'RS'
use shipping_demo::{FlatRate, Parcel, PerKilo, ShippingRule, Zoned};

fn main() {
    let rules: Vec<Box<dyn ShippingRule>> = vec![
        Box::new(FlatRate { price: 4_500 }),
        Box::new(PerKilo { base: 1_000, per_kg: 1_200 }),
        Box::new(Zoned {
            home_city: "Lagos".to_string(),
            local: 2_000,
            national: 5_500,
        }),
    ];

    for parcel in [Parcel::new(800, "Lagos"), Parcel::new(6_500, "Kano")] {
        for rule in &rules {
            println!("{}", rule.quote(&parcel));
        }
        let best = rules
            .iter()
            .min_by_key(|rule| rule.cost(&parcel))
            .expect("at least one rule");
        println!("cheapest for {}: {}", parcel.destination, best.name());
    }

    println!(
        "Box<dyn ShippingRule> is {} bytes, &FlatRate is {} bytes",
        std::mem::size_of::<Box<dyn ShippingRule>>(),
        std::mem::size_of::<&FlatRate>()
    );
}
RS
cargo run -q

The last line shows what dynamic dispatch costs. A Box<dyn ShippingRule> is two pointers wide on a 64-bit machine: one to the value and one to a vtable, a table of the type's method addresses. Each call to rule.cost loads the address from the vtable and jumps there. Compared with the generic cheapest, you pay:

  • One heap allocation per boxed courier.
  • One extra pointer lookup per method call.
  • No inlining across that call, because the compiler cannot see which function it will reach, so it cannot optimise the caller and callee together.

For a list of three couriers this is nothing you could measure. It starts to matter in tight loops over millions of values.

A trait can only be used as dyn if it is dyn compatible. Roughly: its methods take self by reference, do not return Self and have no type parameters of their own. If you later add a method such as fn beats<R: ShippingRule>(&self, other: &R) -> bool to ShippingRule, every dyn ShippingRule in this file stops compiling, unless that method is marked where Self: Sized to keep it off the vtable.

Check it worked

The output lists three quotes per parcel, then a winner. For the Lagos parcel the zoned courier wins (cheapest for Lagos: Zoned); for the 6.5 kg Kano parcel the flat rate wins (cheapest for Kano: Flat rate). The size line reads Box<dyn ShippingRule> is 16 bytes, &FlatRate is 8 bytes.

Step 6 · Implement Display and From for your own types

So far prices print as raw minor units. Add a Money type that prints 4500 as 45.00, and two conversions. Display is the trait behind {}; it cannot be derived, because only you know how a value should read to a person. From converts one type into another, and implementing it gives you .into() in the other direction for free:

Bash
cat >> src/lib.rs <<'RS'

use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Money(pub u64);

impl From<u64> for Money {
    fn from(minor_units: u64) -> Self {
        Money(minor_units)
    }
}

impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad(&format!("{}.{:02}", self.0 / 100, self.0 % 100))
    }
}

impl fmt::Display for Parcel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}.{:03} kg to {}",
            self.weight_g / 1000,
            self.weight_g % 1000,
            self.destination
        )
    }
}

impl<'a> From<(u32, &'a str)> for Parcel {
    fn from((weight_g, destination): (u32, &'a str)) -> Self {
        Parcel::new(weight_g, destination)
    }
}
RS

Money holds a single u64, so it can derive Copy and the ordering traits. The Display for Money uses f.pad rather than write!. pad honours the width and alignment the caller asks for, such as {:>8}; a plain write! ignores them, and right-aligned price columns would come out ragged.

Replace src/main.rs:

Bash
cat > src/main.rs <<'RS'
use shipping_demo::{FlatRate, Money, Parcel, PerKilo, ShippingRule};

fn main() {
    let parcel: Parcel = (2_300, "Kigali").into();
    println!("{parcel}");

    let flat = FlatRate { price: 4_500 };
    let per_kilo = PerKilo { base: 1_000, per_kg: 1_200 };
    let rules: [&dyn ShippingRule; 2] = [&flat, &per_kilo];
    for rule in rules {
        let price: Money = rule.cost(&parcel).into();
        println!("{:<10} {price:>8}", rule.name());
    }

    let total = Money::from(flat.cost(&parcel) + per_kilo.cost(&parcel));
    println!("both: {total}");
}
RS
cargo run -q

A trait object does not have to be boxed: &dyn ShippingRule borrows a value that lives elsewhere, here on the stack, with the same vtable lookup and no allocation. Keeping money as an integer and formatting it only at the edge means a total is never off by a fraction of a kobo or a cent. For real prices, show the currency code next to the number (NGN 45.00, KES 45.00), since the same digits mean very different amounts in different currencies.

Check it worked

The program prints the parcel as 2.300 kg to Kigali, then two rows with the prices lined up on the right (Flat rate with 45.00, Per kilo with 46.00), then both: 91.00.

Step 7 · Choose generics or trait objects for each job

The rule of thumb: use generics when the type is known where the code is compiled, and trait objects when it is only known while the program runs. Put both in one program. Append a function that builds a courier from a name typed by the user:

Bash
cat >> src/lib.rs <<'RS'

pub fn rule_from_name(name: &str) -> Option<Box<dyn ShippingRule>> {
    let rule: Box<dyn ShippingRule> = match name {
        "flat" => Box::new(FlatRate { price: 4_500 }),
        "per-kilo" => Box::new(PerKilo {
            base: 1_000,
            per_kg: 1_200,
        }),
        "zoned" => Box::new(Zoned {
            home_city: "Lagos".to_string(),
            local: 2_000,
            national: 5_500,
        }),
        _ => return None,
    };
    Some(rule)
}
RS

The type annotation on rule lets each match arm's Box<FlatRate>, Box<PerKilo> or Box<Zoned> coerce to Box<dyn ShippingRule>. No generic signature could express this: which type comes back depends on a string that does not exist until the program runs.

Replace src/main.rs with a program that uses the generic cheapest for a fixed set of offers and trait objects for couriers named on the command line:

Bash
cat > src/main.rs <<'RS'
use shipping_demo::{cheapest, rule_from_name, Money, Parcel, PerKilo, ShippingRule};
use std::env;

fn main() {
    let parcel = Parcel::new(2_300, "Lagos");

    // Known when compiling: one concrete type, static dispatch.
    let offers = [
        PerKilo { base: 1_000, per_kg: 1_200 },
        PerKilo { base: 2_500, per_kg: 600 },
    ];
    let best = cheapest(&offers, &parcel).expect("offers is not empty");
    println!("best per-kilo offer: {}", Money::from(best.cost(&parcel)));

    // Known only at run time: trait objects, dynamic dispatch.
    let mut rules: Vec<Box<dyn ShippingRule>> = Vec::new();
    for name in env::args().skip(1) {
        match rule_from_name(&name) {
            Some(rule) => rules.push(rule),
            None => eprintln!("unknown courier rule: {name}"),
        }
    }
    for rule in &rules {
        println!("{:<10} {:>8}", rule.name(), Money::from(rule.cost(&parcel)));
    }
}
RS
cargo run -q -- zoned flat drone

Use this list when you decide:

  • Generics (<T: Trait> or impl Trait): the type is fixed at each call site, you want the fastest code, or you need methods that are not dyn compatible. The cost is compile time and binary size, since every type used gets its own copy of the function.
  • Trait objects (&dyn Trait, Box<dyn Trait>): you need a mixed collection, the type is picked from configuration or user input, or you are writing a plugin point that other code fills in later. The cost is a pointer lookup per call, lost inlining and, for Box, a heap allocation.
  • Return-position impl Trait: one concrete type you want to hide, especially iterators and closures. If different paths need different types, return Box<dyn Trait> instead.

Start with generics, and move to dyn when you hit a mixed list or a run-time choice. Profile before switching for speed alone. When you have finished, delete the folder with rm -rf ~/shipping-demo.

Check it worked

Standard output is three lines: best per-kilo offer: 43.00, then Zoned with 20.00 and Flat rate with 45.00, in the order you typed them. The terminal also shows unknown courier rule: drone, printed to standard error, so the program warns about the typo and carries on. Run cargo run -q -- per-kilo and only the per-kilo row appears, at 46.00.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.