While reading the Explicit capture clauses blog post, I realized that my understanding of rust closures was very superficial. This article is an attempt at explaining what I learned while reading and experimenting on the subject. It starts from the very basics and then explore more complex topics. Note that each title is a link to a rust playground where you can experiment with the code in the section. You probably already know that a closure in rust is a function written with the following syntax: let double_closure = |x| x * 2; assert_eq!(4, double_closure(2)); Written as a regular function it looks like: fn double_function(x: u32) -> u32 { x * 2 } assert_eq!(4, double_function(2)); Very similar. There is actually a small difference between the two, the double_function parameter and return type are u32. On the other hand, because we did not specify any type in double_closure, the default integer type has been picked, namely i32. We can fix that like this: let double_typed_closure = |x: u32| -> u32 { x * 2 }; assert_eq!(4, double_typed_closure(2)); assert_eq!(4, double_typed_closure(2u32)); // assert_eq!(4, double_typed_closure(2u16)); // This would be an error. And for a classic example usage of closures, we can use the Option::map method: assert_eq!(Some(4), Some(2).map(|x| x * 2)); assert_eq!(Some(4), Some(2).map(double_closure)); // double_closure from above assert_eq!(Some(4), Some(2).map(double_function)); // Passing double_function works too! So, it seems closures are just a shorter syntax for functions with type inference. The main difference between closures and functions is that closures can capture variables from their environment while functions can't: let hello = "Hello "; let greeter_closure = |x| String::new() + hello + x; assert_eq!("Hello world", greeter_closure("world")); assert_eq!( Some("Hello world".to_owned()), Some("world").map(greeter_closure) ); Notice how the hello variable is used within the body of the greeter_closure. Let's try that wit...
First seen: 2026-01-24 20:52
Last seen: 2026-01-25 05:53