docs / Getting Started / Closures

Closures

Lambdas are first-class values. They can be stored in variables, passed as arguments, and returned from functions. Closures capture variables from the enclosing scope by value.

use system.io

fn apply(f fn(int) int, x int) int
    f(x)

fn main()
    // Non-capturing lambda
    let square = fn(x int) int: x * x
    println(f"{square(5)}")          // 25

    // Capturing closure — captures `base` by value
    var base = 100
    let add = fn(n int) int: base + n
    println(f"{add(42)}")            // 142

    // Passing closures as arguments
    let double = fn(x int) int: x * 2
    println(f"{apply(double, 7)}")   // 14

At the ABI level, closures are represented as fat pointers (fn_ptr, env_ptr). Captured variables are copied into an environment struct at the point of closure creation.