Some TILs for Rust:

  • When you want a function within a function to capture/have-access-to the context of the parent function, lambdas closures are useful.
fn parent_fn(y: i32) -> i32 {
  let my_closure = |x: i32| x+y;
  my_closure(5)
}
  • closures, however, cannot be recursive. Instead, we have to use a real function and send in any context as explicit parameters.
fn parent_fn(y: i32) -> i32 {
  fn my_inner_fn(x: i32, y: i32) -> i32 {
    if y <= 0 { return 0 }
    x + my_inner_fn(x, y-1)
  }
  my_inner_fn(2, y)
}
  • Since Rust does not allow default argument values (or defaults based on earlier arguments in the list), wrapper functions are the common solution.