Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
JOHNWICK
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Closures
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
Yesterday we covered Error Handling with ?, if you missed it Iâd suggest you check it out first. Error Handling with ? Today weâll be talking about error handling in Rust, specifically the `?` operator, in a way that feels practical and⌠medium.com Imagine youâre writing a web server that processes user requests. Each request needs to be handled based on some condition, like checking if a user is logged in. Instead of writing a separate function for every possible check, you can use a closure , a small, anonymous function that grabs variables from its surroundings and runs when called. Closures in Rust are like portable snippets of logic that carry their context with them, making your code more modular and reusable. In Rust, a closure looks like this: |x| x + 1. Itâs a function without a name, defined inline, that takes an argument x and returns x + 1. But what makes closures special is their ability to âcaptureâ variables from the scope theyâre defined in. Letâs see this in action with a real-world-inspired example. Suppose youâre building a logging system for a Rust application. You want to log messages with a custom prefix, like the name of the module generating the log. Below code is how a closure can help: <pre> fn setup_logger(module_name: &str) -> impl Fn(&str) { let prefix = module_name.to_string(); move |message: &str| println!("{}: {}", prefix, message) } fn main() { let log_auth = setup_logger("Auth"); let log_db = setup_logger("Database"); log_auth("User logged in"); // Prints: Auth: User logged in log_db("Query executed"); // Prints: Database: Query executed } </pre> You can play around with the code here (https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=582b7b5d2c04767e0f51cfa6d8d1374f). In the code above, the closure captures prefix and uses it every time itâs called. The move keyword ensures the closure owns prefix, which is crucial if the closure outlives the function itâs defined in. This is a pattern you might use in a web framework or a CLI tool to keep logging flexible without hardcoding prefixes everywhere. How Closures Work Closures in Rust are unique because they can capture variables in three different ways: by reference (&T), by mutable reference (&mut T), or by value (T). Rustâs ownership system decides which one to use based on what the closure does with the captured variables. This makes closures both powerful and safe, as they play by Rustâs strict borrowing rules. Letâs say youâre working on a task scheduler for a background job system, like processing payments in an e-commerce app. You need to define tasks that depend on some shared configuration, like a retry count. Hereâs how a closure can capture that configuration: <pre> fn schedule_task(max_retries: u32) -> impl FnMut() -> bool { let mut attempts = 0; move || { attempts += 1; println!("Attempt {} of {}", attempts, max_retries); attempts <= max_retries } } fn main() { let mut process_payment = schedule_task(3); while process_payment() { // Simulate processing a payment } // Output: // Attempt 1 of 3 // Attempt 2 of 3 // Attempt 3 of 3 // Attempt 4 of 3 } </pre> You can play around with the code here (https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=9a6ae78dbd4d9aa00f2768ac9ae72718). Here, the closure captures attempts mutably (because it modifies it) and max_retries by value (because it only reads it). The move keyword ensures the closure owns both variables, which is necessary since the closure is returned from the function. This pattern is common in systems where tasks need to track their own state, like retry logic in network calls or job queues. Rustâs compiler is smart enough to figure out the minimal capture mode. If you only read a variable, itâll capture by reference. If you modify it, itâll use a mutable reference or take ownership, depending on the context. This ensures memory safety without you having to micromanage borrowing. Closures and Traits Rust closures implement one or more of three traits: Fn, FnMut, and FnOnce. These traits define how a closure interacts with its captured variables and determine where it can be used. Letâs break them down with a scenario you might face in a real project. Imagine youâre building a data processing pipeline for a Rust-based analytics tool. You need to filter, transform, and aggregate data from a stream of user events. Closures are perfect for defining these steps dynamically. Hereâs how the traits come into play: * Fn: For closures that only read their captured variables. Think of a filter that checks if an eventâs value exceeds a threshold. <pre> fn filter_events(threshold: i32) -> impl Fn(&i32) -> bool { move |value: &i32| *value > threshold } fn main() { let events = vec![10, 5, 20, 3, 15]; let filter = filter_events(10); let filtered: Vec<i32> = events.into_iter().filter(|&x| filter(&x)).collect(); println!("{:?}", filtered); // Prints: [20, 15] } </pre> You can play around with the code here (https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=db7f55f6811735eecc6f74db0d044e7e). This closure implements Fn because it only reads threshold. You can call it multiple times, and itâs safe to use in contexts like iterators or parallel processing (e.g., with the rayon crate). * FnMut: For closures that modify their captured variables. Suppose you want to transform events by adding a running total. <pre> fn transform_events() -> impl FnMut(&mut i32) { let mut total = 0; move |value: &mut i32| { total += *value; *value = total; } } fn main() { let mut events = vec![1, 2, 3]; let mut transform = transform_events(); events.iter_mut().for_each(|x| transform(x)); println!("{:?}", events); // Prints: [1, 3, 6] } </pre> You can play around with the code here (https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=4dd539342100c8a1a1ccce026516b2af). This closure implements FnMut because it modifies total. It can be called multiple times but not concurrently, since it needs exclusive access to total. Youâd use this in sequential pipelines or stateful transformations. <pre> * FnOnce: For closures that consume their captured variables. Imagine logging the final result of your pipeline, but only once. fn finalize_pipeline(result: String) -> impl FnOnce() { move || { println!("Final result: {}", result); } } fn main() { let finalize = finalize_pipeline("Processed 100 events".to_string()); finalize(); // Prints: Final result: Processed 100 events // finalize(); // Error: closure was consumed } </pre> You can play around with the code here (https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=bfcf5da1a20c416dd3b85ffd67592190) This closure implements FnOnce because it takes ownership of result and can only be called once. You might use this for cleanup tasks or one-off notifications in a system. These traits make closures versatile but also ensure Rustâs safety guarantees. For example, you canât accidentally use a FnOnce closure in a loop that expects multiple calls, because the compiler will catch it. Where Closures Shine Now that weâve covered the mechanics, letâs look at some practical scenarios where closures make your life easier in Rust projects. These are drawn from common tasks you might encounter in web development, systems programming, or data processing. 1. Dynamic Request Handling in a Web Server Suppose youâre building a web server using actix-web or hyper. You need to define routes that handle requests based on user roles. Closures let you define these handlers inline, capturing relevant context like a database connection or configuration. <pre> use std::sync::Arc; fn create_handler(role: &str) -> impl Fn(&str) -> String { let role = role.to_string(); move |request: &str| format!("{} request handled for role: {}", request, role) } fn main() { let admin_handler = create_handler("Admin"); let guest_handler = create_handler("Guest"); println!("{}", admin_handler("GET /dashboard")); // GET /dashboard request handled for role: Admin println!("{}", guest_handler("GET /login")); // GET /login request handled for role: Guest } </pre> In a real web server, you might pass these closures to route definitions, capturing shared resources like a connection pool or authentication service. The Arc type (for thread-safe reference counting) often pairs with closures in async contexts to share data safely across threads. 2. Async Task Processing In async Rust, closures are a natural fit for defining tasks that run on an executor like tokio. Imagine a system that processes incoming messages from a queue, like a chat application. You want to apply a transformation to each message based on its source. <pre> use tokio::sync::mpsc; async fn process_messages(mut rx: mpsc::Receiver<String>, transform: impl Fn(&str) -> String) { while let Some(message) = rx.recv().await { println!("Processed: {}", transform(&message)); } } #[tokio::main] async fn main() { let (tx, rx) = mpsc::channel(32); let transformer = |msg: &str| format!("Transformed: {}", msg.to_uppercase()); tokio::spawn(process_messages(rx, transformer)); tx.send("hello".to_string()).await.unwrap(); tx.send("world".to_string()).await.unwrap(); // Output: Processed: Transformed: HELLO // Processed: Transformed: WORLD } </pre> Here, the closure captures no variables (itâs just a simple transformation), but you could easily modify it to capture a configuration or state, like a prefix or a counter. This is common in async systems where you need to define lightweight, reusable logic for processing streams of data. 3. Custom Sorting for a Reporting Tool Letâs say youâre building a reporting tool that sorts customer data based on different criteria, like purchase amount or signup date. Closures let you define custom sorting logic on the fly. <pre> #[derive(Debug)] struct Customer { name: String, purchase_amount: f64, } fn sort_customers(customers: &mut [Customer], sorter: impl Fn(&Customer, &Customer) -> std::cmp::Ordering) { customers.sort_by(|a, b| sorter(a, b)); } fn main() { let mut customers = vec![ Customer { name: "Alice".to_string(), purchase_amount: 100.0 }, Customer { name: "Bob".to_string(), purchase_amount: 200.0 }, ]; let by_amount = |a: &Customer, b: &Customer| b.purchase_amount.partial_cmp(&a.purchase_amount).unwrap(); sort_customers(&mut customers, by_amount); println!("{:?}", customers); // Bob (200.0), Alice (100.0) } </pre> This closure implements Fn and is passed to sort_customers, letting you swap sorting logic without rewriting the function. In a real reporting tool, you might let users select sorting criteria via a UI, and closures make it easy to map those choices to actual logic. Common Pitfalls and How to Avoid Them Closures are powerful, but they come with a few gotchas, especially for developers new to Rustâs ownership model. Here are some common issues you might hit in a project and how to handle them: * If a closure captures a variable by reference and you try to move it elsewhere, Rust will complain. Use move to take ownership if the closure needs to outlive its scope, but be aware this might affect other parts of your code. <pre> let data = vec![1, 2, 3]; let closure = move || println!("{:?}", data); // println!("{:?}", data); // Error: data was moved into the closure * When returning a closure, you need to use impl Fn (or FnMut, FnOnce) because closures have unique, unnameable types. If you need to store closures in a collection, use Box<dyn Fn> to erase the type. fn create_handlers() -> Vec<Box<dyn Fn(&str) -> String>> { vec![ Box::new(|s| format!("Handler 1: {}", s)), Box::new(|s| format!("Handler 2: {}", s)), ] } * Async closures are not yet stable in Rust (as of 2025), so you need to use async blocks or separate async functions for async tasks. For example: let async_task = move || async { println!("Async closure-like task"); }; </pre> Before You Go By understanding how Closures work, how they capture variables and implement traits like Fn, FnMut, and FnOnce, you can use them effectively in real-world projects. Just watch out for borrowing pitfalls and trait bounds, and youâll be writing cleaner, idiomatic Rust code in no time. Read the full article here: https://medium.com/rustaceans/closures-14adc5936391
Summary:
Please note that all contributions to JOHNWICK may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
JOHNWICK:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
Closures
Add topic