1
1
% Closures
2
2
3
- Sometimes it is useful to wrap up a function and free variables for better
4
- clarity and reuse. The _ free variables _ that can be used come from the
5
- enclosing scope and are " closed over" when used in the function. From this, we
6
- get the name " closures" and Rust provides a really great implementation of
3
+ Sometimes it is useful to wrap up a function and _ free variables _ for better
4
+ clarity and reuse. The free variables that can be used come from the
5
+ enclosing scope and are ‘ closed over’ when used in the function. From this, we
6
+ get the name ‘ closures’ and Rust provides a really great implementation of
7
7
them, as we’ll see.
8
8
9
9
# Syntax
@@ -46,10 +46,11 @@ assert_eq!(2, plus_one(1));
46
46
```
47
47
48
48
But we don’t have to. Why is this? Basically, it was chosen for ergonomic
49
- reasons. While specifying the full type for named functions is helpful with
50
- things like documentation and type inference, types within closures are rarely
51
- documented since they’re anonymous, and they don’t cause the kinds of
52
- error-at-a-distance problems that inferring named function types can.
49
+ reasons. While specifying the full type for named functions is helpful with
50
+ things like documentation and type inference, the full type signatures of
51
+ closures are rarely documented since they’re anonymous, and they don’t cause
52
+ the kinds of error-at-a-distance problems that inferring named function types
53
+ can.
53
54
54
55
The second is that the syntax is similar, but a bit different. I’ve added
55
56
spaces here for easier comparison:
@@ -65,7 +66,7 @@ Small differences, but they’re similar.
65
66
# Closures and their environment
66
67
67
68
The environment for a closure can include bindings from its enclosing scope in
68
- addition to parameters and local bindings. It looks like this:
69
+ addition to parameters and local bindings. It looks like this:
69
70
70
71
``` rust
71
72
let num = 5 ;
@@ -454,7 +455,7 @@ autogenerated name.
454
455
The error also points out that the return type is expected to be a reference,
455
456
but what we are trying to return is not. Further, we cannot directly assign a
456
457
` 'static ` lifetime to an object. So we'll take a different approach and return
457
- a " trait object" by ` Box ` ing up the ` Fn ` . This _ almost_ works:
458
+ a ‘ trait object’ by ` Box ` ing up the ` Fn ` . This _ almost_ works:
458
459
459
460
``` rust,ignore
460
461
fn factory() -> Box<Fn(i32) -> i32> {
0 commit comments