@@ -110,25 +110,27 @@ passing two variables: one is an i32, and one is a function."
110
110
Next, let's look at how ` twice ` is defined:
111
111
112
112
``` {rust,ignore}
113
- fn twice( x: i32, f: |i32| -> i32 ) -> i32 {
113
+ fn twice<F: Fn(i32) -> i32>( x: i32, f: F ) -> i32 {
114
114
```
115
115
116
116
` twice ` takes two arguments, ` x ` and ` f ` . That's why we called it with two
117
117
arguments. ` x ` is an ` i32 ` , we've done that a ton of times. ` f ` is a function,
118
- though, and that function takes an ` i32 ` and returns an ` i32 ` . Notice
119
- how the ` | i32| -> i32` syntax looks a lot like our definition of ` square `
120
- above, if we added the return type in:
121
-
122
- ``` {rust}
123
- let square = |&: x: i32| -> i32 { x * x };
124
- // |i32| -> i32
125
- ```
126
-
127
- This function takes an ` i32 ` and returns an ` i32 ` .
118
+ though, and that function takes an ` i32 ` and returns an ` i32 ` . This is
119
+ what the requirement ` Fn( i32) -> i32` for the type parameter ` F ` says.
120
+ You might ask yourself: why do we need to introduce a type parameter here?
121
+ That is because in Rust each closure has its own unique type.
122
+ So, not only do closures with different signatures have different types,
123
+ but different closures with the * same * signature have * different * types!
124
+ You can think of it this way: the behaviour of a closure is part of its type.
125
+ And since we want to support many different closures that all take
126
+ an ` i32 ` and return an ` i32 ` we introduced a type parameter that is able
127
+ to represent all these closures.
128
128
129
129
This is the most complicated function signature we've seen yet! Give it a read
130
130
a few times until you can see how it works. It takes a teeny bit of practice, and
131
- then it's easy.
131
+ then it's easy. The good news is that this kind of passing a closure around
132
+ can be very efficient. With all the type information available at compile-time
133
+ the compiler can do wonders.
132
134
133
135
Finally, ` twice ` returns an ` i32 ` as well.
134
136
0 commit comments