Closure syntax
- Rust course
- Intermediate
- Lesson 42/115
- 4 min
Define closures with the |param| body syntax.
Closure syntax
A closure is an anonymous function that can be assigned to a variable or passed to a function. Parameters go between vertical bars; a single-expression body needs no braces:
let kare = |x: i32| x * x;
let topla = |a: i32, b: i32| a + b;
let selam = || println!("merhaba");
let uzun = |x: i32| {
let y = x * 2;
y + 1
};Closures are called like normal functions: kare(4). Their difference from functions is that they can capture variables from the environment where they are defined.
Comparison with functions
A function and a closure doing the same job:
fn kare_fn(x: i32) -> i32 { x * x }
let kare_cl = |x: i32| -> i32 { x * x };
let kare_kisa = |x| x * x; // types are inferredTypes are mandatory in function signatures because they are part of an API; closures are usually short-lived and local, so their types can be inferred. Closures that capture nothing can also convert to a fn pointer.
Practice First closures
Define the closures kare (|x: i32| x * x) and topla (|a: i32, b: i32| a + b). Print the results of kare(4) and topla(2, 3) separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let kare = |x: i32| x * x;
let topla = |a: i32, b: i32| a + b;
println!("{} {}", kare(4), topla(2, 3));
}Expected output
16 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a closure without parameters written?
- () => expression
- fn() expression
- |_| expression
- || expression Correct answer
Explanation: || is an empty parameter list; |_| takes one parameter and ignores it.
2 Parameter list
let kare = ____ x * x;
let kare = |x: i32| x * x;
Explanation: Closure parameters are written between vertical bars.
3 Closure and result
| Term | Meaning |
|---|---|
(|x: i32| x * x)(4) |
16 |
(|a: i32, b: i32| a + b)(2, 3) |
5 |
(|| 7)() |
7 |
(|x: i32| x - 1)(0) |
-1 |