Code Example Template
let send = |code| send_stroke(code);
let trigger = |x: u32| { x + offset };

Deep-Dive System Documentation

Closures: Context Capturing callbacks

A closure is an anonymous function that can capture variables from its enclosing scope. They are written using pipe boundaries || instead of parentheses.

let active_key = 0x41;

// Closure captures 'active_key' from environment automatically!
let is_active_key = |code| code == active_key;

assert!(is_active_key(0x41));

Trait Category Implementations

The compiler packages closures into anonymous structs implementing one of three built-in traits, depending on how variables are captured:

  1. Fn: Captures variables by reference (&T). Can be invoked multiple times.
  2. FnMut: Captures variables by mutable reference (&mut T). Can mutate variables, can be called multiple times.
  3. FnOnce: Consumes and takes ownership of captured variables. Can only be invoked once.
// FnOnce example capturing by moving ownership
let profile_name = String::from("Vercel");
let run_process = move || {
    let name = profile_name; // owned, moved
    spawn_worker(name);
};

Quick Reference Guide

let add_one = |x| x + 1;
let res = add_one(5);