# 語法

Closure看上去是這樣的：

``    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));``

``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 plus_one = |x| 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;                 ^~~``

``    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);``

``closure.rs:8:19: 8:23 error: use of moved value: `nums` [E0382]closure.rs:8    println!("{:?}", nums);``

``為什么在前面的例子中closure是borrow，而到了這里就變成了move了呢？``

``    let mut num = 5;    let plus_num = || num + 1;    let num2 = &mut num;``
``Error:closure.rs:5:21: 5:24 error: cannot borrow `num` as mutable because it is also borrowed as immutableclosure.rs:5     let num2 = &mut num;``

``    let plus_num = || num + 1;     // 改成如下語句    let mut plue_num = || num += 1;``

``Error:closure.rs:4:17: 4:20 error: cannot borrow `num` as mutable more than once at a timeclosure.rs:4 let num2 = &mut num;``

• by reference: &T
• by mutable reference: &mut T
• by value: T

``    let plus_num = || num + 1;         // 這個只需要引用即可,所以plus_num類型為Fn()    let mut plue_num = || num += 1;    // 這個則需要&mut T，所以plus_num類型為FnMut()    // 這是手冊里的一個例子    // 這是一個沒有實現Copy trait的類型    let movable = Box::new(3);    // `drop` 需要類型T，所以closure環境就需要 by value T.，所以consume類型為FnOnce()    let consume = || {        drop(movable);    // 這里發生了move    };    // 所以這個consume只能執行一次    consume();``

1. let a= 100i32;
2. let a = vec![1,2,3];

# Move closure

``    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);    ``