Skip to content

Checkpoint: A Runtime Rule and a Reporter

The Course
•
32 min study

This checkpoint joins the two directions of behavior from today. The rules come from configuration, so they are trait objects chosen at run time. What happens to each accepted quantity is the caller's business, so it is a callback the caller supplies. Your traversal sits between them: it borrows the rules, applies them to every value and reports the outcome, without owning either the rules or the state the callback changes. That separation is what lets one traversal serve a printer, a counter and a stock update alike.

What you will use

  • Trait objects in a slice. &[Box<dyn Rule>] borrows a list of owned rules of different concrete types.
  • all over the rules. A value is accepted only if every rule allows it, and an empty rule list accepts everything.
  • An FnMut callback. The traversal calls it once per accepted value, and it may change state it captured from the caller.
  • Borrow scopes. The closure's borrow of the caller's state ends when the traversal returns, so the caller can read the result.

Plan before you type

  1. Write accepted(rules: &[Box<dyn Rule>], values: &[u32], mut record: impl FnMut(u32)) -> usize, returning the number of rejected values.
  2. Loop over the values. For each, ask rules.iter().all(...), then either call record or count a rejection.
  3. In main, check [3, 7, 5] against Maximum(5) alone, collecting accepted values into a vector.
  4. Check [3, 4, 7, 6, 2] against Maximum(5) and Even together, summing accepted values with a different closure.
  5. Check an empty rule list against [3, 7], counting accepted values.
Prove the rules are combined with all

Include a value that one rule accepts and another rejects, such as 6 against Maximum(5) and Even. If the traversal used any instead of all, 6 and 3 would be accepted and the total would change from 6 to 15. A test where every rule agrees cannot tell the two apart.

Mistakes worth checking for

  • cannot borrow as mutable inside accepted: the parameter was written record: impl FnMut(u32) without mut. Calling an FnMut needs mutable access to the closure.
  • cannot borrow seen as immutable in main: the closure was stored in a variable and used after the print. Pass it directly, or print after the last use.
  • The empty rule list rejects everything: the code checks rules.iter().any(...) negated, or starts from false. all on an empty iterator is true.
  • The function signature takes Vec<Box<dyn Rule>> by value: the caller loses its rules after one call. Borrow them.
Exercise

Your turn

Write accepted as planned and run the three checks. Print max 5: [3, 5], rejected 1, then max 5 and even: total 6, rejected 3, then no rules: accepted 2, rejected 0.

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() {
    // Pass boxed rules by shared reference and record their accepted values.
}
Hint 1: the idea

The rules decide acceptance; the callback records the decision. Neither needs to know about the other, and the traversal owns neither.

Hint 2: a first step

Build each rule list with an explicit type, let rules: Vec<Box<dyn Rule>> = vec![Box::new(Maximum(5))];, and pass &rules, which coerces to a slice. Iterate with for &value in values to get each u32 by value.

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 }
}

fn accepted(rules: &[Box<dyn Rule>], values: &[u32], mut record: impl FnMut(u32)) -> usize {
    let mut rejected = 0;
    for &value in values {
        if rules.iter().all(|rule| rule.allows(value)) {
            record(value);
        } else {
            rejected += 1;
        }
    }
    rejected
}

fn main() {
    let single: Vec<Box<dyn Rule>> = vec![Box::new(Maximum(5))];
    let mut seen = Vec::new();
    let rejected = accepted(&single, &[3, 7, 5], |value| seen.push(value));
    println!("max 5: {seen:?}, rejected {rejected}");

    let both: Vec<Box<dyn Rule>> = vec![Box::new(Maximum(5)), Box::new(Even)];
    let mut total = 0;
    let rejected = accepted(&both, &[3, 4, 7, 6, 2], |value| total += value);
    println!("max 5 and even: total {total}, rejected {rejected}");

    let none: Vec<Box<dyn Rule>> = Vec::new();
    let mut count = 0;
    let rejected = accepted(&none, &[3, 7], |_| count += 1);
    println!("no rules: accepted {count}, rejected {rejected}");
}
Text
max 5: [3, 5], rejected 1
max 5 and even: total 6, rejected 3
no rules: accepted 2, rejected 0

In the second check, 3 and 7 fail Even, 6 fails Maximum(5), and only 4 and 2 reach the callback. The same function served three different closures, a push, a sum and a count, and each closure's borrow ended when accepted returned, which is why every println! compiles. The empty list accepting everything is the vacuous truth of all; if a real ledger should treat "no rules" as a configuration error, that check belongs where the rules are parsed, not here.

Was this article helpful?

Your response is saved on this device.