Skip to content

Commit f89ba5d

Browse files
committed
Fix some mistakes in HRTB docs
The example code for higher-ranked trait bounds on closures had an unnecessary `mut` which was confusing, and the text referred to an mutable reference which does not exist in the code (and isn't needed). Removed the `mut`s and fixed the text to better describe the actual error for the failing example.
1 parent 2c2552b commit f89ba5d

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

src/doc/book/closures.md

+10-9
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ that takes a reference like so:
327327
fn call_with_ref<F>(some_closure:F) -> i32
328328
where F: Fn(&i32) -> i32 {
329329

330-
let mut value = 0;
330+
let value = 0;
331331
some_closure(&value)
332332
}
333333
```
@@ -340,14 +340,15 @@ fn call_with_ref<'a, F>(some_closure:F) -> i32
340340
where F: Fn(&'a i32) -> i32 {
341341
```
342342

343-
However this presents a problem in our case. When you specify the explicit
344-
lifetime on a function it binds that lifetime to the *entire* scope of the function
345-
instead of just the invocation scope of our closure. This means that the borrow checker
346-
will see a mutable reference in the same lifetime as our immutable reference and fail
347-
to compile.
343+
However, this presents a problem in our case. When a function has an explicit
344+
lifetime parameter, that lifetime must be at least as long as the *entire*
345+
call to that function. The borrow checker will complain that `value` doesn't
346+
live long enough, because it is only in scope after its declaration inside the
347+
function body.
348348

349-
In order to say that we only need the lifetime to be valid for the invocation scope
350-
of the closure we can use Higher-Ranked Trait Bounds with the `for<...>` syntax:
349+
What we need is a closure that can borrow its argument only for its own
350+
invocation scope, not for the outer function's scope. In order to say that,
351+
we can use Higher-Ranked Trait Bounds with the `for<...>` syntax:
351352

352353
```ignore
353354
fn call_with_ref<F>(some_closure:F) -> i32
@@ -362,7 +363,7 @@ expect.
362363
fn call_with_ref<F>(some_closure:F) -> i32
363364
where F: for<'a> Fn(&'a i32) -> i32 {
364365

365-
let mut value = 0;
366+
let value = 0;
366367
some_closure(&value)
367368
}
368369
```

0 commit comments

Comments
 (0)