Sitemap
Rustaceans

Exploring Rust: Insights and Expertise from Rustaceans

Closures

8 min readJul 24, 2025

--

Press enter or click to view image in full size
Image made by Excalidraw

Yesterday we covered Error Handling with ?, if you missed it I’d suggest you check it out first.

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.

--

--

Rustaceans
Rustaceans

Published in Rustaceans

Exploring Rust: Insights and Expertise from Rustaceans

John Philip
John Philip

Written by John Philip

Dev | Life Café | Twitter at @amjohnphilip | Email: dxphilo@gmail.com

No responses yet