Is 'static Bound on generic type mandatory
Asked Answered
F

0

9

I can't figure out why I need a 'static bound in one case (bar) and not the other (baz):

fn f<T>(_input: T) -> bool {
    false
}

fn bar<T>() -> Box<dyn Fn(T) -> bool + 'static>
where
    T: 'static,
{
    Box::new(f::<T>)
}

fn baz<T>() -> Box<dyn Fn(T) -> bool + 'static> {
    Box::new(|x| f::<T>(x))
}

fn main() {
    let f1 = bar::<&usize>();
    let f2 = baz::<&usize>();
    println!("Hello, world! {} {}", f1(&1), f2(&2));
}

Is this a compiler limitation? Otherwise which non-'static type T would break the function bar and why?

I understand about the need for the trait object to live for the 'static lifetime. I think I understand that the closure seems to live for 'static as well. What I don't understand is why f::<T>: 'staticT: 'static

I looked at the function item section in the reference but its not clear to me.

Farreaching answered 8/9 at 15:36 Comment(4)
I recall seeing this before related to async and the Futures they return. I think it's just a quirk of constraint satisfaction.Troublesome
This seems like it could be a bug. You can indeed use non-static lifetimes with baz. IMO bar should compile without the constraint.Freedwoman
It's worth noting that Clippy doesn't suggest replacing |x| f::<T>(x) with f::<T> as it normally would. It seems Clippy knows that wouldn't work here.Freedwoman
See also users.rust-lang.org/t/…Histogen

© 2022 - 2024 — McMap. All rights reserved.