© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
C. MilanesiBeginning Rusthttps://doi.org/10.1007/978-1-4842-7208-4_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, ...

Get Beginning Rust: Get Started with Rust 2021 Edition 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.