Skip to content

Closures

A closure lists every outside variable it uses, after its signature:

fn map_all(items: &Vec<i64>, f: &fn(&i64) -> Str) -> Vec<Str> {
let mut out: Vec<Str> = []
for x in items {
out.push(f(x))
}
return out
}
let offset = 10
let mut count = 0
let items = [1, 2]
let prefix = "#"
let add = fn(x: i64) -> i64 [offset] { return x + offset }
let bump = fn() [&mut count] { count += 1 }
bump()
let names = map_all(&items, &fn(n: &i64) -> Str [&prefix] => prefix + n.to_str())
print(add(1) + names.len())
  • [x] moves (or copies) x into the closure; [mut x] does the same but lets the closure change its own copy; [&x] and [&mut x] borrow.
  • Nothing else from the enclosing function is visible. Capturing is a decision, so it is written down, like everything that crosses a boundary.
  • => expr is shorthand for { return expr }; its return type may be left out. Parameter types may be left out where the expected type says them.
  • The type is fn(A, B) -> R ! E. Named functions are values of that type.
  • A closure that borrows is tied to the variables it borrows: it can be called, or passed as &f to a &fn(...) parameter, but not moved into a struct, collection or function, or returned. Owning closures can go anywhere. This keeps borrows sound without lifetime annotations.
  • Vec methods that take a function borrow it: sort_by (stable; negative means the first argument goes first), map, filter (clones what it keeps), retain, any, all.
  • A by-value capture belongs to the closure, which may run again, so it cannot be moved out (clone it). Closures cannot be cloned.