我没有在Rust文档中找到任何可以解释生命周期elision如何应用于闭包的规则.我们举一个简单的例子:
fn foo(s: &str) {
let id = |x: &str| x;
println!("{}", id(s));
}
fn main() {
foo("string");
}
Run Code Online (Sandbox Code Playgroud)
我认为foo函数中的闭包将类似于以下代码:
fn foo(s: &str) {
struct Id; // A helper structure for closure
impl Id {
fn id(self: Self, x: &str) -> &str { &x }
}
let id = Id; // Creating a closure
println!("{}", id.id(s));
}
Run Code Online (Sandbox Code Playgroud)
后者工作正常,但前者无法编译并产生关于冲突的生命周期要求的长错误消息:
t3.rs:2:24: 2:25 error: cannot infer an appropriate lifetime due to conflicting requirements [E0495]
t3.rs:2 let id = |x: &str| x; …Run Code Online (Sandbox Code Playgroud)