Open gdennie opened 1 year ago
I don't think its outdated because when passing a liftetime to the impl
you have to explicitly specify the lifetime in the calling function as well, but with HRBT as in the example the only place you specify the liftetime is the closure and the function doesn't complain about missing lifetimes.
I think it would be nice to see this explained though, because I did have the question. Why would you not declare the lifetime in on the impl
? Wouldn't that be more explicit?
I know there's a difference, but not what that is.
Actually after I originally posted my comment, I've looked into HRTBs a little deeper and have found a very interesting answer on stackoverflow, essentially what HRTBs are doing is that the lifetime in for<>
is relative to the closure itself defined in the function signature, allowing local methods to be called from inside the body of the function, however, if the lifetime is defined on the function fn foo <'a>(...)
itself and not the closure, local variables automatically will have smaller lifetime then the function itself and you will not be allowed to call the function of a trait for example using local variables.
Now if go back to our example in the book, edit it a bit and use the lifetime on the function itself without HRTB
struct Closure<F> {
data: (u8, u16),
func: F,
}
impl<'a, F> Closure<F>
where F: Fn(&'a (u8, u16)) -> u8,
{
fn call(&'a self) -> u8 {
let local = (10, 15);
(self.func)(&local)
}
}
fn do_it<'b>(data: &'b (u8, u16)) -> u8 {
data.0
}
fn main() {
let clo = Closure {
data: (0, 1),
func: do_it
};
println!("{}", clo.call());
}
if you run the following you'll get
Compiling playground v0.0.1 (/playground)
error[E0597]: `local` does not live long enough
--> src/main.rs:11:21
|
6 | impl<'a, F> Closure<F>
| -- lifetime `'a` defined here
...
10 | let local = (10, 15);
| ----- binding `local` declared here
11 | (self.func)(&local)
| ------------^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `local` is borrowed for `'a`
12 | }
| - `local` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (bin "playground") due to previous error
p.s. this is why I think the author of that page wrote "If we try to naively desugar this code" :)
You can find the detailed explanation with nice examples here - https://stackoverflow.com/a/35595491/10791422
This article seems to be out of date since the stipulation in its early example is easily modified slightly to be valid Rust as demonstrated here on the Rust Playground. Perhaps I am missing something.
As the article states:
However the following is possible...