A closure is an anonymous function written inline. Use it where a function such as map_err accepts another function, avoiding separate named functions for small transformations. section 2.5.5
Rust closure syntax develops incrementally:
- Write parameters between pipe characters: |x, y| x + y. section 2.5.5
- Return a single expression directly, or use braces for a block containing multiple expressions. section 2.5.5
- Usually omit parameter and return types because the surrounding function provides type hints. section 2.5.5
- Use map_err closures to convert validation errors into variants of a custom UsernameError. section 2.5.5
Compact username validation
validate_lowercase(username).map_err(|_| UsernameError::NotLowercase)?; validate_unique(username).map_err(|_| UsernameError::NotUnique)?; section 2.5.5
fn main() {
let add1 = |x: i32, y: i32| -> i32 {x + y};
let add2 = |x: i32, y: i32| x + y; #1
println!("{}", add1(3, 4));
println!("{}", add2(3, 4));
}
Compare explicitly typed and inferred closures that both behave like callable functions. section 2.5.5



















