LEARN VOID / DATA & BEHAVIOR

Functions & closures

Let a function carry the state it needs.

Complete program for the synchronous entry adapter. The result below is the returned integer.

closures.voidDownload source
func make_counter(step: i32) -> func() -> i32:
    var count = 0
    return func() -> i32:
        count += step
        return count

func entry(step: i32) -> i32:
    var next_count = make_counter(step)
    next_count()
    var shared_counter = next_count
    return shared_counter()
Input 5Expected result 10

Return a typed function

make_counter returns func() -> i32. The anonymous function captures a counter starting at zero and the chosen step. These bindings remain available after the factory returns.

Observe shared captured state

With step 5, the first call advances the count to five. Assigning next_count to shared_counter shares the closure state; its next call returns ten. This is the next count, not a sum of several test observations.

Keep copies and callbacks distinct

Ordinary value assignments outside capture retain their copy semantics. Escaping closures retain captured managed references and readonly restrictions. Function values have exact positional signatures; supported named functions, method references and callable structs can also serve as typed callbacks.