0Pricing
Learn Rust Coding · Lesson

Closures

Anonymous functions.

What Is a Closure?

A closure is an anonymous function you can store in a variable and call later. It is written with vertical bars around the parameters.

fn main() {
    let add_one = |x| x + 1;
    println!("{}", add_one(4));
}

Closure Syntax

The parameters go between |...|, followed by the body. With a single expression, no braces are needed.

  • |x| x + 1 — one parameter.
  • |a, b| a + b — two parameters.
fn main() {
    let multiply = |a, b| a * b;
    println!("{}", multiply(3, 5));
}

All lessons in this course

  1. Defining Functions
  2. Expressions and Statements
  3. Closures
  4. Fn, FnMut, FnOnce
← Back to Learn Rust Coding