Higher Ranked Trait Bound and boxed closures lifetime issue

核能气质少年 提交于 2019-12-03 06:44:20

Type parameters have a lifetime bound. That lifetime bound is the shortest of all of the implementor's lifetime parameters. You omitted it on generate_closure_gen, so the compiler inferred it, but if we explicitly wrote it out, the function definition would look like this:

fn generate_closure_gen<'a, C: 'a>() -> Box<Fn(&C)> {
    Box::new(|c: &C| {})
}

Making this change doesn't solve our problem, though.

To understand why, we need to figure out what C is inferred to be. You call the closure with a &'y Parameter<'x>, and the closure accepts for<'b> &'b C, so C is Parameter<'x>. Parameter<'x> has a lifetime parameter, which will have an influence on the lifetime bound on C.

Lifetime parameters in generic functions must be substituted with lifetimes that start before the function call. In this case, this means that the lifetime of any C we pass to the closure must be valid before the call to generate_closure_gen. That's because C is bound to a specific lifetime, not to any lifetime; i.e. when C is Parameter<'x>, the 'x must be known in advance; we can't have a different 'x each time we call the closure. In other words, what you'd like to have is something like this:

fn generate_closure_gen<C: for<'a> 'a>() -> Box<Fn(&C)> {
    Box::new(|c| {})
}

But unfortunately, that isn't legal as of Rust 1.7.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!