LEARN VOID / DATA & BEHAVIOR

Defer & resource cleanup

Make cleanup part of the scope that owns it.

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

cleanup.voidDownload source
# An in-memory model: reserve workspace slots, then release them.
struct workspace:
    available: i32

struct reservation:
    owner: workspace
    slots: i32

func (booking reservation) deinit():
    booking.owner.available += booking.slots

func reserve(space: workspace, slots: i32) -> reservation:
    space.available -= slots
    return reservation(owner = space, slots = slots)

func entry(capacity: i32) -> i32:
    var space = workspace(available = capacity)
    with reserve(space, 2) as booking:
        # The two reserved slots belong to this scope.
        pass
    return space.available
Input 5Expected result 5

Model ownership without an invented API

This is an in-memory workspace reservation, not a file or native-resource API. reserve subtracts two available slots and returns their owner plus the reserved count. Use capacity at least two; availability validation is outside this focused lifetime example.

Release at scope exit

The block owns the booking through with. Its empty body marks where work using the reserved slots would go. Leaving the scope invokes deinit, which restores the slots. Input capacity 5 is temporarily three and returns to 5 before the final read. The return directly observes completed cleanup.

Distinguish with, defer and GC

with cleans at the end of its scope. Reached defer registrations run in reverse order at function exit, including early returns and error propagation. Cleanup is synchronous, and managed deinit uses one-shot release state. Garbage collection reclaims memory but does not invoke resource cleanup; real native wrappers must honor their binding’s lifetime contract.