在显式生命周期中,值的存活时间不够长,但在省略时则活得足够长

Thi*_*rry 5 lifetime rust

我有以下Rust程序,它将一个闭包传递给一个生命周期中的泛型函数'a和一个类型的闭包F,它通过引用一些本地数据来调用闭包:

fn other_function<'a, F>(f: F)
    where F: Fn(&'a u32)
{
    let the_value = 0;
    f(&the_value);
}

fn main() {
    other_function(|_| { /* do nothing */ });
}
Run Code Online (Sandbox Code Playgroud)

这无法编译,并显示以下消息:

<anon>:5:8: 5:17 error: `the_value` does not live long enough
<anon>:5     f(&the_value);
                ^~~~~~~~~
<anon>:3:1: 6:2 note: reference must be valid for the lifetime 'a as defined on the block at 3:0...
<anon>:3 {
<anon>:4     let the_value = 0;
<anon>:5     f(&the_value);
<anon>:6 }
<anon>:4:23: 6:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:22
<anon>:4     let the_value = 0;
<anon>:5     f(&the_value);
<anon>:6 }
error: aborting due to previous error
playpen: application terminated with error code 101
Run Code Online (Sandbox Code Playgroud)

我的最小例子现在可能有点太小,因为对于这个例子,一个有效的解决方案是删除'a,'a.但是,我在一个更复杂的程序中也有类似的情况,其中需要明确的生命周期.

有没有办法手动指定生命周期,以便上述程序被编译器接受?

She*_*ter 6

问题是,来电者other_function得挑寿命,将填补'a,但你要other_function做到这一点.您可以使用一些称为更高排名的特征边界的语法:

fn other_function<F>(f: F)
    where F: for <'a> Fn(&'a u32)
{
    let the_value = 0;
    f(&the_value);
}

fn main() {
    other_function(|_| { /* do nothing */ });
}
Run Code Online (Sandbox Code Playgroud)

正如您所指出的,在这种情况下,'a完全省略它更有意义.你的案件可能需要更复杂的东西,但是你的例子没有别的意义.调用者不可能指定任何与您调用的方法内的堆栈分配变量兼容的生命周期.

  • "排名较高的特质,"有时缩写为HRTB.这是书中没有的唯一语法. (3认同)
  • @Kroltan当我试图解决我的问题时,我发现我需要以某种方式使`Fn(&'a u32)`在某些生命周期中是'a`,但我无法弄清楚它放在哪里.`Fn <'a>(&'a u32)`显然是错的.据我所知,'for`的目的正是为了在那里增加一生. (2认同)