值在明确的生命周期内不会存在足够长的时间,但在省略时会存在足够长的时间
Value does not live long enough with explicit lifetime, but does live long enough when omitted
我有以下 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 */ });
}
编译失败,并显示以下消息:
<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
我的最小示例现在可能有点 太,因为对于此示例,有效的解决方案是删除 'a,
和 'a
。但是,我在一个更复杂的程序中遇到了类似的情况,其中似乎需要明确的生命周期。
有没有办法手动指定生命周期,使上述程序被编译器接受?
问题是 other_function
的 caller 可以选择将填充 'a
的生命周期,但你想要 other_function
去做吧。您可以使用一些名为 higher ranked trait bounds:
的语法
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 */ });
}
正如您所指出的,在这种情况下,完全省略 'a
更有意义。您的案例可能需要更复杂的东西,但对于您的示例,其他任何事情都没有意义。调用者不可能在您调用的方法中指定任何与堆栈分配变量兼容的生命周期。
我有以下 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 */ });
}
编译失败,并显示以下消息:
<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
我的最小示例现在可能有点 太,因为对于此示例,有效的解决方案是删除 'a,
和 'a
。但是,我在一个更复杂的程序中遇到了类似的情况,其中似乎需要明确的生命周期。
有没有办法手动指定生命周期,使上述程序被编译器接受?
问题是 other_function
的 caller 可以选择将填充 'a
的生命周期,但你想要 other_function
去做吧。您可以使用一些名为 higher ranked trait bounds:
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 */ });
}
正如您所指出的,在这种情况下,完全省略 'a
更有意义。您的案例可能需要更复杂的东西,但对于您的示例,其他任何事情都没有意义。调用者不可能在您调用的方法中指定任何与堆栈分配变量兼容的生命周期。