typestar

Storing closures in Rust

A closure has an unnameable type, so a struct stores it boxed behind Fn.

struct Rule {
    name: &'static str,
    test: Box<dyn Fn(&str) -> bool>,
}

fn main() {
    let min_len = 4;
    let rules = vec![
        Rule {
            name: "long enough",
            test: Box::new(move |s: &str| s.len() >= min_len),
        },
        Rule {
            name: "lower case",
            test: Box::new(|s: &str| s.chars().all(|c| !c.is_uppercase())),
        },
    ];

    for candidate in ["rust", "Go"] {
        for rule in &rules {
            println!("{candidate} {}: {}", rule.name, (rule.test)(candidate));
        }
    }
}

How it works

  1. Box<dyn Fn(..) -> ..> gives the field a nameable type.
  2. FnMut is the bound when the closure mutates its captures.
  3. Generics avoid the box when one type per struct is enough.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
424
Tokens
159
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 1 of 1 in Stored behavior, step 10 of 11 in Lifetimes & interior mutability.

← Previous Next →