ske*_*lix 3 closures lifetime rust borrow-checker
fn foo(c: char) -> impl Fn() -> i32 {
|| bar(c)
}
fn bar(_: char) -> i32 {
42
}
Run Code Online (Sandbox Code Playgroud)
这会引发错误
error[E0597]: `c` does not live long enough
--> src/lib.rs:2:12
|
2 | || bar(c)
| -- ^ borrowed value does not live long enough
| |
| value captured here
3 | }
| -
| |
| `c` dropped here while still borrowed
| borrow later used here
Run Code Online (Sandbox Code Playgroud)
我认为像这样的原始类型char是默认复制的;为什么我需要显式move地 ( move || bar(c)) 来编译代码?
您的说法是正确char的Copy,但棘手的是执行复制的时间。
假设该Copy特征有一个名为 的方法copy,类似于Clone::clone。作为编译器执行操作的示例,您的闭包将变为:
|| {
let c = Copy::copy(&c);
bar(c)
}
Run Code Online (Sandbox Code Playgroud)
闭包仅c通过引用捕获,因为这就是调用闭包时执行复制所需的全部内容。通过返回闭包,您将尝试将引用返回到本地,这是被禁止的。
使用强制闭包按值move捕获。c
也可以看看:
| 归档时间: |
|
| 查看次数: |
509 次 |
| 最近记录: |