2026-01-24
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( 2 u32 )); // 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:
... continue reading