如何从函数返回Rust闭包?

时间:2014-12-29 03:48:58

标签: closures rust

尝试学习Rust,似乎我很难找到如何以0.13(每晚)返回一个函数。我的基本示例是尝试处理不可变参数,因此我希望下面的内容能够正常工作。当我在线阅读时,似乎在0.13中行为会发生变化(因此我在网上看到的所有内容似乎都无法发挥作用)。

$ rustc --version
rustc 0.13.0-nightly (62fb41c32 2014-12-23 02:41:48 +0000)

刚刚到达http://doc.rust-lang.org/0.12.0/guide.html#accepting-closures-as-arguments,下一个合乎逻辑的步骤是返回一个闭包。当我这样做时,编译器说我不能

#[test]
fn test_fn_return_closure() {
  fn sum(x: int) -> |int| -> int {
    |y| { x + y }
  }

  let add3 = sum(3i);
  let result: int = add3(5i);

  assert!(result == 8i);
}

/rust-lang-intro/closures/tests/lib.rs:98:21: 98:33 error: explicit lifetime bound required
/rust-lang-intro/closures/tests/lib.rs:98   fn sum(x: int) -> |int| -> int {
                                                                                                   ^~~~~~~~~~~~
error: aborting due to previous error
Could not compile `closures`.

我尝试返回引用以查看是否有帮助

let sum = |x: int| {
  &|y: int| { x + y }
};
let add3 = *(sum(3i));

但是当你尝试使用它时,你会得到一个更加冗长的错误

/rust-lang-intro/closures/tests/lib.rs:102:6: 102:24 error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
/rust-lang-intro/closures/tests/lib.rs:102     &|y: int| { x + y }
                                                ^~~~~~~~~~~~~~~~~~
/rust-lang-intro/closures/tests/lib.rs:105:14: 105:25 note: first, the lifetime cannot outlive the expression at 105:13...
/rust-lang-intro/closures/tests/lib.rs:105   let add3 = *(sum(3i));
                                                        ^~~~~~~~~~~
/rust-lang-intro/closures/tests/lib.rs:105:14: 105:25 note: ...so that pointer is not dereferenced outside its lifetime
/rust-lang-intro/closures/tests/lib.rs:105   let add3 = *(sum(3i));
                                                        ^~~~~~~~~~~
/rust-lang-intro/closures/tests/lib.rs:102:6: 102:24 note: but, the lifetime must be valid for the expression at 102:5...
/rust-lang-intro/closures/tests/lib.rs:102     &|y: int| { x + y }
                                                ^~~~~~~~~~~~~~~~~~
/rust-lang-intro/closures/tests/lib.rs:102:6: 102:24 note: ...so type `|int| -> int` of expression is valid during the expression
/rust-lang-intro/closures/tests/lib.rs:102     &|y: int| { x + y }
                                                                                     ^~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `closures`.

所以,我假设我需要保存指针,并且只在需要时才取消引用,但似乎错误消息基本相同。

1 个答案:

答案 0 :(得分:2)

在目前的1.1.0时代,Rust已有详细记载。

#[cfg(test)]
mod tests {
    // the `type` is not needed but it makes it easier if you will
    // be using it in other function declarations.
    type Adder = Fn(i32) -> i32;

    fn sum(x: i32) -> Box<Adder> {
        Box::new(move |n: i32| x + n)
    }

    #[test]
    fn it_works() {
        let foo = sum(2);
        assert_eq!(5, foo(3));
    }
}

有关详细信息,请参阅the Rust docs