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 | Borrow Closure | |
|---|---|---|
| Definition |
A move closure captures variables from its environment by taking
ownership of them (i.e.,
moving them)
|
A borrow closure captures variables by borrowing them (i.e., creating references to them) |
.iter() .map() .collect()
pipeline in Rust is a functional pattern that transforms a collection of input items into a new collection of a different type, element by element.
3 stages:
.iter(): Takes JSON array & creates an iterator to look at each item (m) one by one
.map(|m| { ... }): runs once for every single element
Option Chaining:
.get("name"): Try to find a field named "name".
.or_else(|| m.get("model")): If "name" isn't there, fall back and try looking for "model" instead.
.and_then(|x| x.as_str()): If a field was found, confirm it is actually a valid JSON string.
.map(|s| s.to_string()): If it is a string, convert it from a borrowed &str slice into an owned String
.collect(): collects all the elements into a new collection (Vec, HashMap, etc.)