在正常函数和定义为闭包的函数之间似乎存在生命周期推断上的差异.请考虑以下最小示例:
fn foo(f: &String) -> &str {
f
}
fn bar() {
|f: &String| -> &str { f };
}
编译器(带有--edition=2021
的Rustc 1.69.0)接受foo
,但拒绝bar
中的闭包(这是与foo相同的函数),并出现错误
error: lifetime may not live long enough
--> clos.rs:8:33
|
8 | move |f: &String| -> &str { f };
| - - ^ returning this value requires that `'1` must outlive `'2`
| | |
| | let's call the lifetime of this reference `'2`
| let's call the lifetime of this reference `'1`
在foo
的情况下,我的理解是编译器将其go 掉
fn foo<'a>(f: &'a String) -> &'a str { ... }
为什么它不为关闭做同样的事情呢?有没有什么方法可以让我自己手动指定生存期(特别是,我应该把<'a>
放在哪里来声明生存期)?