Exploring Rust closures.
This article is part of a series starting with Learning Rust by Contrasting with TypeScript: Part 1 .
Let us walk through the examples in the Rust Book Functional Language Features: Iterators and Closures section and contrast them with TypeScript .
The first part of the section, Closures: Anonymous Functions that Can Capture Their Environment , goes through building an elaborate example of demonstrating Rust closures as anonymous functions. The confusing thing here, given the title of the section, is that this example does not use any features that are closure-like (from a TypeScript perspective).
The final solution is src/main.rs .
In going through the example, another confusing thing was that it felt odd to need to use the generic T as shown below.
My first inclination was to do something like the following:
Turns out, the key here is that Fn is a trait and as such needs to be treated as such.
The TypeScript example, src/index.ts , is essentially the same; just swapping out closures for arrow functions, structs for classes and Options for null handling.
One key difference, however, between Rust and TypeScript is that in TypeScript , we can also pass functions (in addition to arrow function) as parameters; not so in Rust .
With Rust , closures (not functions) can also use (also referred to as capturing) variables from enclosing scopes in much the same way variables are used as parameters when calling functions, e.g., copying, moving, borrowing, etc.
The key difference between captured variables and parameters, however, is that variables are captured at closure creation time while parameters are passed at closure execution time.
In the following example, x is captured by the equal_to_x closure as a copy (just like an i32 would be copied into the function’s execution scope as a parameter).
Much like Rust closures, TypeScript functions capture variables from enclosing scopes at function creation time; stored the function’s closure.
— MDN — Closures
Let us examine TypeScript closures in a TypeScript example based on the previous Rust example.
The next section, Processing a Series of Items with Iterators , explores the use of closures in the context of iterating through a Vec (vector).
In TypeScript , the solution is very similar:
Rust has first-class support for implementing custom implementations of the Iterator trait.
Interestingly enough, TypeScript has a comparable Iterator feature. But…
Continue learning about smart pointers in Learning Rust by Contrasting with TypeScript: Part 13 .