传递 lambda 周围

由于 lambda 函数本身就是值,因此将它们存储在集合中,将它们传递给函数等,就像使用其他值一样。

// This function takes two integers and a function that performs some operation on the two arguments
fn apply_function<T>(a: i32, b: i32, func: T) -> i32 where T: Fn(i32, i32) -> i32 {
    // apply the passed function to arguments a and b
    func(a, b)
}

// let's define three lambdas, each operating on the same parameters
let sum = |a, b| a + b;
let product = |a, b| a * b;
let diff = |a, b| a - b;

// And now let's pass them to apply_function along with some arbitary values
println!("3 + 6 = {}", apply_function(3, 6, sum));
println!("-4 * 9 = {}", apply_function(-4, 9, product));
println!("7 - (-3) = {}", apply_function(7, -3, diff));

这将打印:

3 + 6 = 9
-4 * 9 = -36
7 - (-3) = 10