# 闭包的语法

## 基本形式

let plus_one = |x: i32| x + 1;

assert_eq!(2, plus_one(1));

let plus_two = |x| {
let mut result: i32 = x;

result += 1;
result += 1;

result
};

assert_eq!(4, plus_two(2));

let plus_one = |x: i32| -> i32 { x + 1 };

assert_eq!(2, plus_one(1));

fn  plus_one_v1   (x: i32) -> i32 { x + 1 }
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32|          x + 1  ;

## 捕获变量

let num = 5;
let plus_num = |x: i32| x + num;

assert_eq!(10, plus_num(5));

let mut num = 5;
let plus_num = |x: i32| x + num;

let y = &mut num;

error: cannot borrow num as mutable because it is also borrowed as immutable
let y = &mut num;
^~~
note: previous borrow of num occurs here due to use in closure; the immutable
borrow prevents subsequent moves or mutable borrows of num until the borrow
ends
let plus_num = |x| x + num;
^~~~~~~~~~~
note: previous borrow ends here
fn main() {
let mut num = 5;
let plus_num = |x| x + num;

let y = &mut num;
}
^

let mut num = 5;
{
let plus_num = |x: i32| x + num;

} // plus_num goes out of scope, borrow of num ends

let y = &mut num;

let nums = vec![1, 2, 3];

let takes_nums = || nums;

println!("{:?}", nums);

note: nums moved into closure environment here because it has type
[closure(()) -> collections::vec::Vec<i32>], which is non-copyable
let takes_nums = || nums;
^~~~~~~

Vec<T>拥有它内容的所有权，而且由于这个原因，当我们在闭包中引用它时，我们必须取得nums的所有权。这与我们传递nums给一个取得它所有权的函数一样。

## move闭包

let num = 5;

let owns_num = move |x: i32| x + num;

let mut num = 5;

{
let mut add_num = |x: i32| num += x;

add_num(5);
}

assert_eq!(10, num);

let mut num = 5;

{
let mut add_num = move |x: i32| num += x;

add_num(5);
}

assert_eq!(5, num);