Skip to content

Own Interchangeable Rules with Box and dyn

The Course
•
30 min study

The ledger needs stock rules: a maximum, an even-quantity rule for items sold in pairs, perhaps a minimum. Which rules apply to an item is configuration, known only at run time, and one item may need several at once. A generic function such as fn check<R: Rule>(rule: &R) cannot express that. The compiler makes a separate copy of a generic function for each concrete type, called monomorphization, so every type must be known at compile time, and a Vec<R> holds only one type.

A trait object such as dyn Rule erases the concrete type. A reference to one, &dyn Rule, is a wide pointer: one pointer to the data and one to a table of function pointers for that type, called a vtable. Calls go through the table at run time, which is dynamic dispatch. Because different implementations have different sizes, dyn Rule itself has no size known at compile time, so you always use it behind a pointer. Box<dyn Rule> owns its rule on the heap; &dyn Rule borrows one.

Predict and run

Which quantities pass both rules?

Predict, then run Rust
trait Rule {
    fn allows(&self, quantity: u32) -> bool;
}

struct Maximum(u32);
struct Even;

impl Rule for Maximum {
    fn allows(&self, quantity: u32) -> bool { quantity <= self.0 }
}
impl Rule for Even {
    fn allows(&self, quantity: u32) -> bool { quantity % 2 == 0 }
}
fn main() {
    let rules: Vec<Box<dyn Rule>> = vec![Box::new(Maximum(10)), Box::new(Even)];
    for quantity in [8, 9, 12] {
        println!("{quantity}: {}", rules.iter().all(|rule| rule.allows(quantity)));
    }
}
Check your prediction
Text
8: true
9: false
12: false

9 fails Even and 12 fails Maximum(10), so only 8 passes both. all stops at the first rule that says no. Remove Box::new(Even) from the vector and predict the line for 9 before you run it: it becomes 9: true, while 12 still fails. The type annotation on rules matters. Without it, the compiler would infer the element type from the first box, Box<Maximum>, and reject the second.

Why a generic collection cannot do this

Try the same list without trait objects:

Rust
let rules = vec![Maximum(10), Even];

The compiler reports error[E0308]: mismatched types: the vector's element type is fixed as Maximum by its first element, and Even is a different type. Generics give you one concrete type per use, chosen at compile time. That is their strength: each call is a direct function call the optimizer can inline, and there is no heap allocation. Trait objects trade that away for a single type that many implementations share. The costs are one heap allocation per Box, an indirect call per method, and lost inlining. For a handful of rules per stock update those costs are negligible; in a tight numeric loop over millions of values, a generic or an enum is usually better.

An enum is the third option. enum Rule { Maximum(u32), Even } with a match in allows is fast and needs no boxes, but the set of rules is closed: adding one means editing the enum and every match. A trait is open: another module, or a user of your library, can add a rule without touching yours.

Build rules from configuration

The real reason to reach for Box<dyn Rule> is that the rule list is decided at run time. Below, text such as max:10 chooses the implementation. A default method describe shows that trait objects can call provided methods too.

Choose rules from text at run time Rust
trait Rule {
    fn allows(&self, quantity: u32) -> bool;
    fn describe(&self) -> String { String::from("custom rule") }
}

struct Maximum(u32);
struct Even;

impl Rule for Maximum {
    fn allows(&self, quantity: u32) -> bool { quantity <= self.0 }
    fn describe(&self) -> String { format!("at most {}", self.0) }
}
impl Rule for Even {
    fn allows(&self, quantity: u32) -> bool { quantity % 2 == 0 }
}

fn parse_rule(text: &str) -> Result<Box<dyn Rule>, String> {
    match text.split_once(':') {
        Some(("max", limit)) => {
            let limit = limit.parse().map_err(|_| format!("bad limit in {text:?}"))?;
            Ok(Box::new(Maximum(limit)))
        }
        None if text == "even" => Ok(Box::new(Even)),
        _ => Err(format!("unknown rule {text:?}")),
    }
}

fn main() {
    let config = "max:10,even";
    let rules: Vec<Box<dyn Rule>> = config.split(',').map(parse_rule).collect::<Result<_, _>>().unwrap();
    for rule in &rules {
        println!("rule: {}", rule.describe());
    }
    println!("6 allowed: {}", rules.iter().all(|rule| rule.allows(6)));
    println!("{}", parse_rule("min:3").err().unwrap());
    let wide = std::mem::size_of::<&dyn Rule>() == 2 * std::mem::size_of::<usize>();
    println!("&dyn Rule is two pointers wide: {wide}");
}
Text
rule: at most 10
rule: custom rule
6 allowed: true
unknown rule "min:3"
&dyn Rule is two pointers wide: true

Each arm of parse_rule returns a different concrete box, and the return type Box<dyn Rule> converts each one to the trait object. The last line confirms the wide-pointer layout: data pointer plus vtable pointer. .err().unwrap() is used instead of unwrap_err() because unwrap_err would need Box<dyn Rule> to implement Debug.

Not every trait can be a trait object

A vtable can only hold methods the compiler can call without knowing the concrete type. A method that returns Self, has no self receiver, or has its own generic type parameters breaks that. Add a constructor to the trait and the boxes stop compiling:

Rust
trait Rule {
    fn allows(&self, quantity: u32) -> bool;
    fn named(name: &str) -> Self;
}

Using dyn Rule now fails with error[E0038], which says the trait Rule is not dyn compatible. Older compilers and books call the same property "object safe". The fix the compiler suggests is to add where Self: Sized to named, which excludes that one method from the vtable while keeping it available on concrete types.

Borrow trait objects in parameters

Store Box<dyn Rule> where you own the rules, such as in a configuration struct. In function parameters, take &dyn Rule or &[Box<dyn Rule>]. A function that only calls allows has no reason to take ownership, and borrowing lets callers keep their rules for the next update.

Practice

Exercise

Your turn

Add a Minimum rule and combine it with Maximum in a Vec<Box<dyn Rule>> so that 3 through 8 inclusive are accepted. Test 2, 3, 8 and 9 against the expected results false, true, true, false, and print Composed rules passed.

Your working space Rust
trait Rule {
    fn allows(&self, quantity: u32) -> bool;
}

struct Maximum(u32);
struct Even;

impl Rule for Maximum {
    fn allows(&self, quantity: u32) -> bool { quantity <= self.0 }
}
impl Rule for Even {
    fn allows(&self, quantity: u32) -> bool { quantity % 2 == 0 }
}
fn main() {
    // Add Minimum above main, then compose its rule with Maximum.
}
Hint 1: the idea

Each rule decides one constraint. The caller combines them with all, so the range is the overlap of "at least 3" and "at most 8".

Hint 2: a first step

Write struct Minimum(u32); and implement Rule for it with quantity >= self.0. Test the two values on each edge: 2 and 3, then 8 and 9.

Worked solution
Run the solution Rust
trait Rule {
    fn allows(&self, quantity: u32) -> bool;
}

struct Maximum(u32);
struct Even;

impl Rule for Maximum {
    fn allows(&self, quantity: u32) -> bool { quantity <= self.0 }
}
impl Rule for Even {
    fn allows(&self, quantity: u32) -> bool { quantity % 2 == 0 }
}

struct Minimum(u32);
impl Rule for Minimum {
    fn allows(&self, quantity: u32) -> bool { quantity >= self.0 }
}

fn main() {
    let rules: Vec<Box<dyn Rule>> = vec![Box::new(Minimum(3)), Box::new(Maximum(8))];
    for (quantity, expected) in [(2, false), (3, true), (8, true), (9, false)] {
        assert_eq!(rules.iter().all(|rule| rule.allows(quantity)), expected);
    }
    println!("Composed rules passed");
}
Text
Composed rules passed

Minimum was added without changing Maximum, Even or the loop, which is the open extension a trait gives you and an enum does not. The vector owns both boxes and frees them when it leaves scope. Even is unused here, and the compiler warns about that; it is kept so the rule set matches the other examples. Next you will pass behavior in the other direction: a callback that the caller supplies.

Was this article helpful?

Your response is saved on this device.