Closures
Anonymous functions.
Closures is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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));
}Multi-line Closures
For more than one statement, wrap the body in curly braces, just like a function.
fn main() {
let describe = |n: i32| {
let doubled = n * 2;
println!("{} doubled is {}", n, doubled);
};
describe(7);
}Capturing the Environment
Unlike a plain function, a closure can capture variables from the surrounding scope and use them inside.
fn main() {
let factor = 10;
let scale = |x| x * factor;
println!("{}", scale(5));
}Type Inference in Closures
Closures usually infer their parameter and return types from how they are used, so annotations are optional.
You may add types for clarity when needed.
fn main() {
let greet = |name: &str| -> String {
format!("Hello, {}!", name)
};
println!("{}", greet("Rust"));
}Closures as Arguments
Many standard methods accept a closure. For example map applies a closure to each item.
fn main() {
let nums = vec![1, 2, 3];
let doubled: Vec<i32> = nums.iter().map(|x| x * 2).collect();
println!("{:?}", doubled);
}Filtering with Closures
The filter method keeps only items for which the closure returns true.
fn main() {
let nums = vec![1, 2, 3, 4, 5, 6];
let evens: Vec<i32> = nums.into_iter().filter(|x| x % 2 == 0).collect();
println!("{:?}", evens);
}Storing Closures
Closures have unique anonymous types, but you can store them in a variable and reuse them.
fn main() {
let is_even = |n: i32| n % 2 == 0;
println!("{} {}", is_even(4), is_even(7));
}Closures vs Functions
Differences:
- Functions cannot capture surrounding variables; closures can.
- Closures are anonymous and often short.
- Closure types are usually inferred.
fn main() {
let base = 100;
let bonus = |earned: i32| earned + base;
println!("{}", bonus(25));
}Returning Computed Values
Combine closures with iterators to compute results in a clean, expressive pipeline.
fn main() {
let nums = vec![10, 20, 30];
let total: i32 = nums.iter().map(|x| x + 1).sum();
println!("total {}", total);
}Closures Capture by Reference
By default a closure borrows the captured variables. You can still read them outside afterward (when only borrowed).
fn main() {
let name = String::from("Ada");
let printer = || println!("Name: {}", name);
printer();
println!("still usable: {}", name);
}Quick Check
Recall a key capability of closures.
Recap
Closures in Rust:
- Anonymous functions written as
|params| body. - Can capture variables from their environment.
- Types are usually inferred.
- Widely used with iterator methods like
mapandfilter.
fn main() {
let tax = 0.2;
let with_tax = |price: f64| price * (1.0 + tax);
println!("{}", with_tax(50.0));
}Frequently asked questions
Is the “Closures” lesson free?
Yes — the full text of “Closures” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Closures”?
Anonymous functions. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Closures” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.