【发布时间】:2014-11-16 00:18:12
【问题描述】:
以下代码无法编译。
fn main() {
let foo = bar(8);
println!("Trying `foo` with 4: {:d}", foo(4));
println!("Trying `foo` with 8: {:d}", foo(8));
println!("Trying `foo` with 13: {:d}", foo(13));
}
//
fn bar(x: int) -> (|int| -> int) {
|n: int| -> int {
if n < x { return n }
x
}
}
错误如下。
11:32 error: explicit lifetime bound required
.../hello/src/main.rs:11 fn bar(x: int) -> (|int| -> int) {
^~~~~~~~~~~~
我将整数参数按值传递给bar。为什么 Rust 关心按值传递的整数的生命周期?编写这样一个返回闭包的函数的正确方法是什么?谢谢。
编辑
我在手册中找到了以下内容。 In the simplest and least-expensive form (analogous to a || { } expression), the lambda expression captures its environment by reference, effectively borrowing pointers to all outer variables mentioned inside the function. Alternately, the compiler may infer that a lambda expression should copy or move values (depending on their type.) from the environment into the lambda expression's captured environment.
是否有关于编译器如何推断是否通过引用捕获外部变量、复制它们或移动它们的进一步规范?评估标准是什么,它们的应用顺序是什么?这是否记录在案(缺少阅读编译器的代码)?
【问题讨论】:
标签: rust