Tsallaka zuwa abun ciki
Justice Tech School

Rust Closures

A closure is an anonymous function written with |params| body. It can capture variables from its surroundings. Use move to take ownership.

Example
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 { f(x) }
fn main() {
    let factor = 3;
    let times = |n| n * factor;
    println!("{}", times(5));
    println!("{}", apply(|x| x + 100, 1));
}

Result

15
101

Exercise

Double x.

let f = |x| x  2;

Quiz Test

What are closure parameters written between?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.