What is Higher-Ranked Trait Bounds HRTB

Higher-Ranked Trait Bounds (HRTB) ensure a generic type implements a trait for all possible lifetimes, enabling flexible closure and function pointer usage.

Higher-Ranked Trait Bounds (HRTB) allow a generic function or type to accept a trait implementation that works for any lifetime, not just a specific one. This is essential when a closure or function pointer must borrow data for an arbitrary duration.

fn for_each<F>(v: &[i32], f: F) 
where
    F: Fn(&i32), // Standard bound: works for one specific lifetime
{
    for x in v { f(x); }
}

// HRTB: The closure must work for ANY lifetime 'a
fn for_each_hrtb<F>(v: &[i32], f: F) 
where
    for<'a> F: Fn(&'a i32), 
{
    for x in v { f(x); }
}

In the for_each_hrtb example, the for<'a> syntax before the trait bound tells the compiler that F must implement Fn for every possible lifetime 'a, enabling the closure to accept references with varying lifetimes.