[][src]Function tao_of_rust::ch06::closures::closures

pub fn closures()

闭包

Base usage: 将计数函数改为闭包形式(Rust 2015)

fn counter(i: i32) -> Box<Fn(i32) -> i32> {
    Box::new(move |n: i32| n + i )
}
fn main() {
    let f = counter(3);
    assert_eq!(4, f(1));
}Run

Base usage: 将计数函数改为闭包形式 (Rust 2018)

fn counter(i: i32) -> impl Fn(i32) -> i32 {
    move |n: i32|{ n + i }
}
fn main() {
    let f = counter(3);
    assert_eq!(4, f(1));
}Run

Base usage: 闭包参数可以接收任意类型

fn val() -> i32 { 5 }
fn main(){
    let add = |a: fn() -> i32, (b, c)| (a)() + b + c;
    let r = add(val, (2, 3));
    assert_eq!(r, 10);
}Run

Base usage: 定义一模一样的闭包也不是同一个类型

fn main(){
    let c1 = || {};
    let c2 = || {};
    let v = [c1, c2];
}Run