尝试学习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`.因此,我假设我需要保存指针,并且只在需要时取消引用,但似乎错误消息基本上是相同的。
发布于 2015-08-05 02:33:16
在当前的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。
https://stackoverflow.com/questions/27683144
复制相似问题