© Carlo Milanesi 2018
Carlo MilanesiBeginning Rusthttps://doi.org/10.1007/978-1-4842-3468-6_13

13. Defining Closures

Carlo Milanesi1 
(1)
Bergamo, Italy
 
In this chapter, you will learn:
  • Why there is a need for anonymous inline functions, with type inference for the arguments and the return value type, without having to write braces, and which can access the variables that are alive at the function definition point

  • How such lightweight functions, named “closures”, can be declared and invoked

The Need for “Disposable” Functions

The Rust way to sort an array in ascending order is this:

let mut arr = [4, 8, 1, 10, 0, 45, 12, 7];
arr.sort();
print!("{:?}", arr);

This will print: "[0, 1, 4, 7, 8, 10, 12, 45]";

But if you want to sort it in descending order, ...

Get Beginning Rust: From Novice to Professional now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.