Tutorial by Examples

// A simple adder function defined as a lambda expression. // Unlike with regular functions, parameter types often may be omitted because the // compiler can infer their types let adder = |a, b| a + b; // Lambdas can span across multiple lines, like normal functions. let multiplier = |a: i32, ...
Unlike regular functions, lambda expressions can capture their environments. Such lambdas are called closures. // variable definition outside the lambda expression... let lucky_number: usize = 663; // but the our function can access it anyway, thanks to the closures let print_lucky_number = ...
// lambda expressions can have explicitly annotated return types let floor_func = |x: f64| -> i64 { x.floor() as i64 };
Since lambda functions are values themselves, you store them in collections, pass them to functions, etc like you would with other values. // 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) -> ...
Returning lambdas (or closures) from functions can be tricky because they implement traits and thus their exact size is rarely known. // Box in the return type moves the function from the stack to the heap fn curried_adder(a: i32) -> Box<Fn(i32) -> i32> { // 'move' applies move se...

Page 1 of 1