rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.82k stars 262 forks source link

Higher Ranked Trait Bounds (HRTB) article appears to be out of date #412

Open gdennie opened 1 year ago

gdennie commented 1 year ago

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:

// NOTE: `&'b data.0` and `'x: {` is not valid syntax!
struct Closure<F> {
    data: (u8, u16),
    func: F,
}

impl<F> Closure<F>
    // where F: Fn(&'??? (u8, u16)) -> &'??? u8,
{
    fn call<'a>(&'a self) -> &'a u8 {
        (self.func)(&self.data)
    }
}

fn do_it<'b>(data: &'b (u8, u16)) -> &'b u8 { 
    &'b data.0       // <--- not valid Rust
}

fn main() {
    'x: {                 // <-- not valid Rust
        let clo = Closure { 
            data: (0, 1), 
            func: do_it 
        };
        println!("{}", clo.call());
    }
}

How on earth are we supposed to express the lifetimes on F's trait bound? 
We need to provide some lifetime there, but the lifetime we care about can't 
be named until we enter the body of call! 

However the following is possible...

struct Closure<F> {
    data: (u8, u16),
    func: F,
}

impl<'a, F> Closure<F>
    where F: Fn(&'a (u8, u16)) -> &'a u8,
{
    fn call(&'a self) -> &'a u8 {
        (self.func)(&self.data)
    }
}

fn do_it<'b>(data: &'b (u8, u16)) -> &'b u8 { 
    &data.0 
}

fn main() {
    let clo = Closure { 
        data: (0, 1), 
        func: do_it 
    };
    println!("{}", clo.call());
}
pwbh commented 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.

spikespaz commented 11 months ago

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.

pwbh commented 11 months ago

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

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c17f3e61f906e7c044deb9aa4a272bef

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