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. allover the rules. A value is accepted only if every rule allows it, and an empty rule list accepts everything.- An
FnMutcallback. 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
- Write
accepted(rules: &[Box<dyn Rule>], values: &[u32], mut record: impl FnMut(u32)) -> usize, returning the number of rejected values. - Loop over the values. For each, ask
rules.iter().all(...), then either callrecordor count a rejection. - In
main, check[3, 7, 5]againstMaximum(5)alone, collecting accepted values into a vector. - Check
[3, 4, 7, 6, 2]againstMaximum(5)andEventogether, summing accepted values with a different closure. - 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 mutableinsideaccepted: the parameter was writtenrecord: impl FnMut(u32)withoutmut. Calling anFnMutneeds mutable access to the closure.cannot borrow seen as immutableinmain: 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 fromfalse.allon an empty iterator istrue. - The function signature takes
Vec<Box<dyn Rule>>by value: the caller loses its rules after one call. Borrow them.
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.
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
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}");
}max 5: [3, 5], rejected 1
max 5 and even: total 6, rejected 3
no rules: accepted 2, rejected 0In 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.
Completion is saved in this browser only. It does not measure mastery.