为什么在返回捕获 Copy 类型的闭包时需要 move 关键字?

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)) 来编译代码?

She*_*ter 6

您的说法是正确charCopy,但棘手的是执行复制的时间。

假设该Copy特征有一个名为 的方法copy,类似于Clone::clone。作为编译器执行操作的示例,您的闭包将变为:

|| {
    let c = Copy::copy(&c);
    bar(c)
}
Run Code Online (Sandbox Code Playgroud)

闭包仅c通过引用捕获,因为这就是调用闭包时执行复制所需的全部内容。通过返回闭包,您将尝试将引用返回到本地,这是被禁止的。

使用强制闭包按值move捕获。c

也可以看看:


归档时间:

查看次数:

509 次

最近记录:

3 年,11 月 前