liveBook · Manning

Closure

As explained in Refactoring to Rust

A closure is an anonymous function value that can be written inline and passed to or returned from other functions.

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

How Refactoring to Rust covers it

How deep it goes
Explains syntax, bodies, type inference, and error-mapping applications, but stops short of deeper closure mechanics.
Examples
Demonstrates addition closures and username validation that maps lowercase and uniqueness failures.
What it assumes
Assumes functions, Result, and map_err while teaching closure syntax and type inference directly.
What you can do after
Apply it via map_err to replace small named error-conversion functions with concise inline transformations.
How it connects
Connects closures to functions, map_err, Result, custom errors, and early error returns.

Also explained in

Compare how 20 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.