LEARN VOID / DATA & BEHAVIOR
Defer & resource cleanup
Make cleanup part of the scope that owns it.
# An in-memory model of a workspace with scope-owned cleanup.
struct temporary_workspace:
item_count: i32
func (workspace temporary_workspace) deinit():
workspace.item_count = 0
func entry(item_count: i32) -> i32:
var processed = 0
with temporary_workspace(item_count = item_count) as workspace:
processed = workspace.item_count * 2
return processedGive temporary state an owner
This small, in-memory workspace is a teaching model for scoped cleanup. It holds an item count and clears that state in deinit. It does not pretend to open a file, allocate a foreign buffer or use an unavailable library API.
Keep its lifetime in one scope
with owns cleanup of the workspace for its block. The body processes the count and saves its result. Leaving the block invokes deinit before execution reaches the final return. Input 5 produces 10.
Garbage collection handles unreachable managed memory separately. Real external-resource wrappers use deterministic cleanup to release their supported native resources.
Use defer for function-exit work
defer is another cleanup tool: reached defers run in reverse registration order when the function exits, including an early return or error propagation. Unlike with, it is tied to function exit rather than just the surrounding block. Resource cleanup is synchronous.