傳遞 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