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 8This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 8Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together