[][src]Function tao_of_rust::ch02::function::closure

pub fn closure()

闭包

Basic usage:

pub fn closure(){
    let out = 42;
    // 普通函数
    // fn  add(i: i32, j: i32) -> i32 { i + j + out}
    fn  add(i: i32, j: i32) -> i32 { i + j }
    // 定义类型标注的闭包
    let closure_annotated = |i: i32, j: i32| -> i32 { i + j + out};
    // 如果没有类型标注则由编译器推断类型
    let closure_inferred  = |i, j| i + j + out;
    let i = 1;
    let j = 2;
    assert_eq!(3, add(i, j));
    assert_eq!(45, closure_annotated(i, j));
    assert_eq!(45, closure_inferred(i, j));
}
closure();Run