Closure = Lambda(C++)
-
Closure is a function-like construct that can capture variables from the
environment in which it is defined.
| Rust (Closure) | C++ (Lambda) | |
|---|---|---|
| Can capture variables from their surrounding environment | Yes | Yes |
| Syntax | |...| { ... } | [ ] (parameters) { ... } |
| Different Types | Move, Borrow Closure | There are no types in lambda |
| Can place break in closure? |
No. You can do return. But rust does not allow break due to ownership and borrow check rules |
Yes |
Closure Types
Move Closure
-
A move closure captures variables from its environment by taking
ownership of them (i.e.,
moving them). Example
fn main() {
let x = 10;
let closure = || {
println!("Value of x: {}", x);
};
closure(); // This is a move closure since it captures 'x' by moving it.
// 'x' cannot be used after this point, as it has been moved into the closure.
}
Borrow Closure
-
A borrow closure captures variables by
borrowing them (i.e.,
creating references to them)