CodeBlanks Logo Icon CodeBlanks

Summary - Closures

Combine closures and move to build a counter-generating function.

Closures summary

A closure: |parameters| body. Types are inferred on first use and then fixed. It captures the environment by reading, modifying or taking ownership (move), and implements Fn, FnMut or FnOnce accordingly. It's passed to functions with a generic bound (F: Fn(i32) -> i32) and returned with impl Fn. To keep different closures in the same collection, Box<dyn Fn(..)> is needed, because every closure has a different type.

An operation table

Building a table of named closures is handy for command handlers or calculators:

let islemler: Vec<(&str, Box<dyn Fn(i32) -> i32>)> = vec![
    ("iki katı", Box::new(|x| x * 2)),
    ("kare", Box::new(|x| x * x)),
    ("eksi", Box::new(|x| -x)),
];
for (ad, f) in &islemler {
    println!("{ad}: {}", f(7));
}

Practice Operation table

Build the Vec<(&str, Box<dyn Fn(i32) -> i32>)> table above and print each operation for 7 as ad: result on separate lines.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let islemler: Vec<(&str, Box<dyn Fn(i32) -> i32>)> = vec![
        ("iki katı", Box::new(|x| x * 2)),
        ("kare", Box::new(|x| x * x)),
        ("eksi", Box::new(|x| -x)),
    ];
    for (ad, f) in &islemler {
        println!("{}: {}", ad, f(7));
    }
}

Expected output

iki katı: 14
kare: 49
eksi: -7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why doesn't <code>vec![|x| x + 1, |x| x * 2]</code> compile?

  • x has no type
  • It compiles
  • The two closures have different types; a vector needs one type Correct answer
  • Closures can't go into vectors

Explanation: Every closure is a unique type. With Box<dyn Fn(i32) -> i32> they all become the same trait object type.

2 Common closure type

Question
let f: Box<____ Fn(i32) -> i32> = Box::new(|x| x * 2);
Answer
let f: Box<dyn Fn(i32) -> i32> = Box::new(|x| x * 2);

Explanation: A dyn Fn trait object is used to gather different closures under one type.

3 Operation and result for 7

Term Meaning
double 14
kare 49
eksi -7
|x| x % 3 1

All lessons in Intermediate