Skip to content

[feedback] docs unclear for: higher ranked trait bounds #480

@Z3NTL3

Description

@Z3NTL3

In my experience, I've had some bad time trying to understand why I need higher ranked trait bounds and the what's the use of them.

I would like if the examples in the page could be more clear.

To understand why my experience was bad, think flow-wise of the following below about how I took the things I've been reading on this page:

Snippet 1

#[allow(unused)]
struct Closure<F> {
    data: (u8, u16),
    func: F,
}

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

#[allow(unused)]
fn do_it(data: &(u8, u16)) -> &u8 { &data.0 }

Snippet 2

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

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

fn do_it(data: &(u8, u16)) -> &u8 { &data.0 }
  • I was reading through the rust nomicon related to higher ranked trait bounds ye
  • It gave me the second snipppet as an example for when you need to use higher ranked trait bounds

But if i can do what's on snippet 1 why would i need it
it clearly states this reasoning for that:

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! Also, that isn't some fixed lifetime; call works with any lifetime &self happens to have at that point.

if Self can take any lifetime ensuring that it wll be satisfied under one circumstance which Self should be valid for

why do i need for<'a> , its just accepts any lifetime with a requirement for the reference the closure takes and returns remain valid

Thanks in advance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions