From d4b70fe6c683a8a292353b60bdce40ecfe9f5962 Mon Sep 17 00:00:00 2001 From: Sebastian Gesemann Date: Fri, 9 Jan 2015 20:08:14 +0100 Subject: [PATCH] documentation: Fix boxed closure left-over and add some words on why we use a type parameter for closures. --- src/doc/trpl/closures.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/doc/trpl/closures.md b/src/doc/trpl/closures.md index 6413b90ee71..23f5109c5bd 100644 --- a/src/doc/trpl/closures.md +++ b/src/doc/trpl/closures.md @@ -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: ```{rust,ignore} -fn twice(x: i32, f: |i32| -> i32) -> i32 { +fn twice i32>(x: i32, f: F) -> i32 { ``` `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, -though, and that function takes an `i32` and returns an `i32`. Notice -how the `|i32| -> i32` syntax looks a lot like our definition of `square` -above, if we added the return type in: - -```{rust} -let square = |&: x: i32| -> i32 { x * x }; -// |i32| -> i32 -``` - -This function takes an `i32` and returns an `i32`. +though, and that function takes an `i32` and returns an `i32`. This is +what the requirement `Fn(i32) -> i32` for the type parameter `F` says. +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. +So, not only do closures with different signatures have different types, +but different closures with the *same* signature have *different* types! +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 +to represent all these closures. 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 -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.