Hello! Welcome back.
In our last lesson, we explored how Option<T> helps us write robust code by handling the absence of a value. We also got a glimpse of how methods like map() and unwrap_or_else() use small, inline functions as arguments. You might have noticed the | | syntax and wondered what that was all about. Those were closures, and today, we're diving deep into them.
This lesson will formally introduce you to closures, which are anonymous functions that you can store in variables, pass to other functions, and that can capture variables from their environment. Understanding closures is a significant step toward mastering idiomatic Rust. It's a key feature that enables powerful functional programming patterns, which are especially useful for the next topic we'll cover: iterators. For your goal of working with embedded systems, mastering these high-level abstractions is crucial for writing efficient and expressive code that still runs close to the metal.
What is a Closure?
At its core, a closure is an anonymous function. Unlike functions defined with the fn keyword, closures don't have a name and can be defined right where you need them. Their power comes from three main characteristics:
- They are anonymous.
- They can be saved in a variable or passed as an argument to another function.
- They can capture values from the scope in which they are defined.
Let's look at the basic syntax. A closure is defined using a pair of vertical pipes | | for its parameters, followed by the body of the function.
// A function that adds two numbers
fn add_function(a: i32, b: i32) -> i32 {
a + b
}
// A closure that does the same thing
let add_closure = |a: i32, b: i32| -> i32 { a + b };
// Calling both
let sum1 = add_function(2, 3);
let sum2 = add_closure(2, 3);
println!("Sum from function: {}", sum1);
println!("Sum from closure: {}", sum2);
While they look similar, closures have some unique properties that make them incredibly flexible.
Understanding Rust Closures aka. Anonymous Functions 🦀 💻
This video by Trevor Sullivan provides an excellent introduction to the fundamental syntax of closures and how they differ from regular functions.
Please watch the following segments: The first part explains the basic syntax, comparing the | | of a closure to the ( ) of a function, and discussing the optional use of curly braces for single-line versus multi-line bodies. Next, watch the section on parameters and type inference. This highlights a key feature: the compiler can often figure out the types of your parameters and return value, making closures very concise. Finally, watch the clip on multi-line closures, which shows how to write more complex logic and handle return values.
The ability of the compiler to infer types is a significant advantage. While you can add type annotations for clarity, you often don't need to. However, once the compiler infers a type for a closure's parameters, that type is locked in for that closure.
Capturing the Environment
The most powerful feature of closures is their ability to "capture" variables from their surrounding scope. A regular function is self-contained, but a closure can access variables from the function it was defined in, without needing them to be passed as arguments.

This "capturing" can happen in three ways, which map directly to Rust's ownership and borrowing rules:
- Immutable Borrow (
&T): The closure reads the captured variable but doesn't change it. - Mutable Borrow (
&mut T): The closure modifies the captured variable. - Take Ownership (
T): The closure takes ownership of the variable. Themovekeyword is used to force this behavior.
The OneUptime article provides clean and concise examples for each of the three capture methods.
Please read the section titled "Capturing Variables". Pay attention to the keywords mut and move and how they change the closure's interaction with its environment. The example for move in the context of threads is particularly important, as this is a primary use case you'll encounter later when we discuss concurrency.
The Fn Family of Traits
So, how does Rust manage this? Behind the scenes, every closure implements one or more of the Fn traits. The compiler automatically determines which traits to implement based on how the closure interacts with its captured variables.
The three traits are:
FnOnce: This trait is for closures that can be called at least once. All closures implementFnOnce. Closures that take ownership of a captured variable can only be called once, because the variable is moved out of the closure's environment.FnMut: This trait is for closures that can be called multiple times and can mutate their captured environment. It inherits fromFnOnce.Fn: This trait is for closures that can be called multiple times without changing their environment (i.e., they only use immutable borrows or capture nothing). It inherits fromFnMut.
This creates a hierarchy. A closure that implements Fn also implements FnMut and FnOnce. A closure that implements FnMut also implements FnOnce.

When you write a function that accepts a closure as an argument, you use these traits as trait bounds to specify what kind of closure you need.
Closures - The Rust Programming Language
The official Rust book provides a detailed explanation of the Fn traits and how they are used in function signatures.
Please read the section titled "Moving Captured Values Out of Closures". Focus on these key points: The definitions of FnOnce, FnMut, and Fn. The analysis of unwrap_or_else, which we saw in the last lesson. Notice its signature requires FnOnce(), making it very flexible. The example with sort_by_key, which requires FnMut because it must call the closure multiple times (once for each element being sorted). The code in Listing 13-8, which tries to use an FnOnce closure where FnMut is needed, is an excellent illustration of how the compiler enforces these rules.
Forcing Ownership with move
As mentioned, you can force a closure to take ownership of its captured variables by using the move keyword before the parameter list.
let x = vec![1, 2, 3];
// This closure borrows `x`
let borrows = || println!("x: {:?}", x);
borrows();
println!("x can still be used here: {:?}", x);
// This closure takes ownership of `y`
let y = vec![4, 5, 6];
let takes_ownership = move || println!("y: {:?}", y);
takes_ownership();
// The next line would cause a compile error because `y` has been moved.
// println!("y can no longer be used here: {:?}", y);
This is essential when working with threads, as you need to move data into the new thread to ensure it remains valid, but it's also useful anytime you want to decouple the closure's lifetime from the scope where it was created.
Conclusion
In this lesson, we've formally defined closures and explored their core features. They are a cornerstone of idiomatic Rust, bridging the gap between imperative and functional programming styles.
Here are the key takeaways:
- Closures are anonymous functions with a concise syntax:
|parameters| body. - They can capture variables from their environment via immutable borrow, mutable borrow, or by taking ownership.
- The Rust compiler infers the types for a closure's parameters and return value.
- The way a closure captures its environment determines which of the
Fn,FnMut, orFnOncetraits it implements. These traits are used as bounds on functions that accept closures. - The
movekeyword forces a closure to take ownership of its captured variables, which is crucial for concurrency and controlling lifetimes.
You've now seen how closures are defined and how they work. In our next lesson, we will put this knowledge to immediate and extensive use. We'll explore iterators, a powerful feature for processing sequences of data. You will see how combining iterators with closures allows you to write incredibly expressive, efficient, and safe code for tasks like filtering, transforming, and aggregating data.