2024-05-06 20:40:05 +00:00
|
|
|
---
|
2024-10-30 17:04:36 +00:00
|
|
|
date: 20200923
|
2024-05-06 20:40:05 +00:00
|
|
|
id: 8353cf5c-2d2d-480a-b957-0e90da847e1c
|
|
|
|
title: Rust Closures
|
|
|
|
---
|
|
|
|
|
|
|
|
# Syntax
|
|
|
|
|
|
|
|
## Long
|
|
|
|
|
|
|
|
``` rust
|
|
|
|
fn main() {
|
|
|
|
let double_closure = |num: u32| -> u32 { 2 * num };
|
|
|
|
|
|
|
|
println!("2 times 3 = {}", double_closure(3));
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Abbreviated
|
|
|
|
|
|
|
|
``` rust
|
|
|
|
fn main() {
|
|
|
|
let double_closure = |num| 2 * num;
|
|
|
|
|
|
|
|
println!("2 times 3 = {}", double_closure(3));
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
# Closure variable scope
|
|
|
|
|
|
|
|
Unlike [Rust functions](20200827170931-functions_macros) Closures can
|
|
|
|
capture their environment and access variables from the scope in which
|
|
|
|
they're defined:
|
|
|
|
|
|
|
|
``` rust
|
|
|
|
fn main() {
|
|
|
|
let x = 4;
|
|
|
|
|
|
|
|
let equal_to_x = |z| z == x;
|
|
|
|
|
|
|
|
let y = 4;
|
|
|
|
|
|
|
|
assert!(equal_to_x(y));
|
|
|
|
}
|
|
|
|
```
|