Menu
Coddy logo textTech

What is a Closure?

Part of the Logic & Flow section of Coddy's Rust journey — lesson 59 of 66.

A closure is an anonymous function that you can store in a variable or pass as an argument to other functions. Unlike regular functions that you define with the fn keyword, closures are created inline and don't need a name.

The basic syntax for a closure uses vertical bars to define parameters, followed by the function body:

|param1, param2| { 
    // function body goes here
}

Here's a simple example of a closure that adds two numbers:

let add = |x, y| x + y;
let result = add(5, 3); // result is 8
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

Cheat sheet

A closure is an anonymous function that can be stored in a variable or passed as an argument. Closures use vertical bars || to define parameters:

|param1, param2| { 
    // function body
}

Example of a closure:

let add = |x, y| x + y;
let result = add(5, 3); // result is 8

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow