Name stored callbacks
A dictionary can associate names with owned callbacks from one factory. Calling
a callback that changes its captured state needs a mutable borrow: use
get_mut to keep the callback registered,
or pop to take ownership.
def counter(total: i64) -> Closure[[], Result[i64, OverflowError[i64]]]:
def [mut total]() -> Result[i64, OverflowError[i64]]:
total = total + 1
Ok(total)
def main() -> Result[(), AllocError | IoError | OverflowError[i64]]:
mut callbacks = {"open": counter(10), "close": counter(100)}?
match callbacks.get_mut("open"):
case Some(callback):
print(callback()?)?
case Nothing:
print("no open handler")?
match callbacks.pop("close"):
case Some(callback):
mut owned = callback
print(owned()?)?
case Nothing:
print("no close handler")?
print(len(callbacks))?
Ok(())
11
101
1
Replacing a registered callback drops the old captured state. Inserting a new key
may grow the dictionary and returns Result. A live borrow of any callback
protects the dictionary against replacement, removal, and growth.
The callback itself cannot be a dictionary key or a set element: closures do not define equality or hashing. The dictionary’s value type preserves its concrete factory identity, rather than accepting every callback with the same signature. Use explicit boxing to store different shared-call environments behind one signature.