Closures
Closures (also called lambdas or anonymous functions) are functions that can capture variables from their enclosing scope. They are a core building block for functional-style programming, callbacks, and iterator chains in Vex.
Syntax
Vex closure syntax uses pipe-delimited parameters directly followed by the body expression or block. No => is needed:
// Basic closure: |params| expression
let double = |x: i32| x * 2
// Multi-parameter
let add = |a: i32, b: i32| a + b
// No parameters
let greet = || $println("Hello")
// Multi-statement body with braces
let compute = |x: i32, y: i32| {
let temp = x * y
let result = temp + 10
return result
}Calling a Closure
Call closures with the same () syntax as regular functions:
let triple = |n: i32| n * 3
let six = triple(2) // 6
let nine = triple(3) // 9Type Inference
Closure parameter types can often be inferred from context:
// Named function reference:
fn timesTwo(x: i32): i32 { return x * 2 }
let number: Option<i32> = Some(5)
let doubled: Option<i32> = number.map(timesTwo)
// An explicitly typed closure is another way to provide the callback:
let doubledAgain: Option<i32> = number.map(|x: i32| x * 2)An expected callable type supplies context for a closure. Explicit parameter types also document the callback contract and distinguish a borrowed &T from an owned T. This matters for generic collection transforms and for callbacks whose input and output types differ. See the Option and Result examples.
Capture Modes
Closures may capture variables from their enclosing scope. The compiler analyzes how each capture is used and checks its ownership and lifetime. Do not infer the physical representation solely from the source syntax: the compiler can copy a read-only scalar into the environment, borrow storage, or transfer ownership depending on the value and use.
Shared (Immutable) Capture
When a closure only reads captured variables:
let multiplier = 10
// Reads multiplier. A Copy scalar can be copied into the environment.
let scale = |x: i32| x * multiplier
let result = scale(5) // 50
// multiplier is still usable hereMutable Capture
When a closure modifies captured variables:
let! counter = 0
// Captures counter by mutable reference
let increment = || {
counter += 1
}
increment()
increment()
// counter is now 2Move Capture
Some uses transfer ownership into a closure environment. The exact outcome depends on the captured type and how the closure is used. Do not assume that a move-only value remains usable after ownership transfers. If a callback needs repeatable access, borrow for a bounded call or give it an explicitly owned handle with the appropriate sharing policy. A closure returning or retaining a reference cannot extend the lifetime of its referent.
A runnable capture example
This example exercises a read-only scalar, a mutable capture, an ordinary callback and a returned closure. Save it as capture-example.vx:
fn applyTwice(f: fn(i32): i32, x: i32): i32 { return f(f(x)); }
fn makeMultiplier(factor: i32): fn(i32): i32 { return |x: i32| x * factor; }
fn addOne(x: i32): i32 { return x + 1; }
fn main(): i32 {
let multiplier = 10;
let scale = |x: i32| x * multiplier;
$println(scale(5));
$println(multiplier);
let! counter = 0;
let increment = || { counter += 1; };
increment(); increment();
$println(counter);
let addThree = |n: i32| n + 3;
$println(applyTwice(addThree, 10));
let timesFive = makeMultiplier(5);
$println(timesFive(10));
let named: fn(i32): i32 = addOne;
$println(named(41));
return 0;
}vex run capture-example.vx prints:
50
10
2
16
50
42Closure Types
Use a function-value signature to describe the callback interface independently of its captures:
// Function that accepts any callable returning i32
fn applyTwice(f: fn(i32): i32, x: i32): i32 {
return f(f(x))
}
let addThree = |n: i32| n + 3
let result = applyTwice(addThree, 10) // (10+3)+3 = 16Closures as Callbacks
Closures are the standard way to pass behavior into higher-order functions:
fn sumWhere(values: &Vec<i32>, predicate: fn(i32): bool): i32 {
let! total = 0;
for value in values {
if predicate(*value) { total += *value; }
}
return total;
}The vector remains borrowed for the call, and the callback receives an integer copy. With [1, 2, 3, 4, 5, 6] stored in a Vec<i32>, sumWhere(&numbers, |n: i32| n % 2 == 0) returns 12. For library adapters, use the receiver and callback signatures on the Vec, Option, and Result pages. An array does not gain those methods merely because it contains the same element type.
Closures with go Blocks
go blocks capture the values they use. Ownership, borrowing and lifetime checks still apply; inspect the diagnostics for the captured types rather than assuming that every capture has the same representation:
let! messages = Channel.new<string>(10)
let prefix = "Msg: "
// The block uses both prefix and messages.
go {
let text = prefix + "hello from goroutine"
messages.send(text)
}
let received = <-messagesClosures vs Function Pointers
| Feature | Closure | Named Vex function as a value |
|---|---|---|
| Captures | May use an environment | Does not capture local variables |
| Native callable | Entry point plus environment/context | Uses the Vex callable representation as well |
| Cost | Depends on capture, lifetime, lowering and optimization | Depends on lowering and optimization |
| Foreign callback | Requires an explicitly supported foreign adapter and lifetime contract | Also requires the exact foreign ABI and a supported adapter |
The native implementation represents a Vex function value with a code pointer and an environment/context pointer. Environment storage depends on the captures and may outlive the defining scope when supported. This is an internal implementation detail, not a stable public or C ABI. Do not assume a native fn(...) value is one pointer or that either kind of callable is directly interchangeable with a C callback. See Function Types and FFI callbacks.
// Named function as a native Vex callable; no local capture.
let fp: fn(i32): i32 = someTopLevelFn
// Closure: can capture, used for local callbacks
let closure = |x| x + capturedValueReturning Closures
An escaping closure must retain valid captures for its lifetime. Allocation and capture strategy are implementation details and may vary with the compiler:
fn makeMultiplier(factor: i32): fn(i32): i32 {
// This closure escapes the function and retains the scalar factor.
return |x: i32| x * factor
}
let timesFive = makeMultiplier(5)
let result = timesFive(10) // 50Best Practices
- Use the shortest closure form (
|x| x * 2) when the body is a single expression. - Use brace-delimited bodies for multi-statement closures.
- Let type inference work -- annotate parameter types only when the compiler asks for it.
- Be aware of capture and ownership: reads may copy or borrow, mutation requires appropriate access, and some uses transfer ownership.
- For
goblocks, be explicit about which variables are used inside to avoid accidental captures. - For FFI callbacks, verify the foreign ABI, adapter, context lifetime and thread rules; a native
fn(T): Ralone is not sufficient.
Related Pages
- Function Types --
fn(T): Rpointers - Loops & Labels -- closures in iteration
- Async -- closures in async context