Merge pull request #20820 from sellibitze/closure-doc

Closure documentation: Fix boxed closure left-over

Reviewed-by: steveklabnik
This commit is contained in:
bors 2015-01-12 00:21:23 +00:00
commit 8e0bb03841

View File

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