Defining a Simple Closure
Part of the Logic & Flow section of Coddy's Rust journey — lesson 60 of 66.
Now that you understand what closures are, let's learn how to define and use them in your code. The simplest way to create a closure is to assign it to a variable, which allows you to call it later.
Here's how you define a basic closure that takes no parameters:
let my_closure = || {
println!("Hello from the closure!");
};Notice the empty vertical bars || - this indicates that the closure takes no arguments. The curly braces contain the code that runs when you call the closure.
To call your closure, you use it just like a function by adding parentheses after the variable name:
let my_closure = || {
println!("Hello from the closure!");
};
my_closure(); // This calls the closure and prints the messageChallenge
EasyYou will receive a single input containing a message. Create a closure that takes no parameters and prints this message. Store the closure in a variable, then call it to display the message.
Requirements:
- Read the input message and trim whitespace
- Create a closure using
||syntax that prints the message - Store the closure in a variable
- Call the closure to execute it
Input:
- A single line containing a message (e.g.,
Welcome to Rust!)
Output:
- The message printed by the closure
Cheat sheet
A closure is defined using vertical bars || and can be stored in a variable:
let my_closure = || {
println!("Hello from the closure!");
};To call a closure, use parentheses after the variable name:
my_closure(); // Executes the closureTry it yourself
use std::io;
fn main() {
// Read input
let mut message = String::new();
io::stdin().read_line(&mut message).expect("Failed to read line");
let message = message.trim();
// TODO: Create a closure that prints the message and store it in a variable
// TODO: Call the closure to print the message
}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