Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Consume a callback

Use OnceCallable for a function that owns and calls its callback once. It accepts named functions, reusable closures, and one-shot closures.

pub def run[T, F: OnceCallable[[], T]](callback: F) -> T:
    mut owned = callback
    owned()
import callbacks

def defer[T](value: T) -> OnceClosure[[], T]:
    def once [value]() -> T:
        value

def main() -> Result[(), AllocError | IoError]:
    take = defer([3, 5]?)
    print(callbacks.run(take))?
    Ok(())
[3, 5]

OnceClosure describes the concrete value returned by defer. OnceCallable describes what the generic run function can accept. Passing take transfers ownership; calling it again afterward is an error. The mutable local inside run also permits reusable callbacks that update private captured state.