rust functional

  • Closures, a function-like construct you can store in a variable
  • Iterators, a way of processing a series of elements
  • How to use these two features to improve the I/O project in Chapter 12
  • The performance of these two features (Spoiler alert: they’re faster than you might think!)

Closure

Closures: Anonymous Functions that Can Capture Their Environment

Rust’s closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they’re defined.

#![allow(unused_variables)]
fn main() {
use std::thread;
use std::time::Duration;

let expensive_closure = |num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
};
expensive_closure(5);
}

if has multiple parameter

|param1, param2|

can add annotation for clarity

#![allow(unused_variables)]
fn main() {
use std::thread;
use std::time::Duration;

let expensive_closure = |num: u32| -> u32 {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
};
}

generic parameter

#![allow(unused_variables)]
fn main() {
struct Cacher<T>
where T: Fn(u32) -> u32
{
calculation: T,
value: Option<u32>,
}
}

The Cacher struct has a calculation field of the generic type T. The trait bounds on T specify that it’s a closure by using the Fn trait. Any closure we want to store in the calculation field must have one u32 parameter (specified within the parentheses after Fn) and must return a u32 (specified after the ->).