Expand description
Support for closures in wasm-bindgen
This module defines the ScopedClosure type which is used to pass Rust closures
to JavaScript. All closures are unwind safe by default: panics are caught and converted to
JavaScript exceptions when built with panic=unwind.
§Immutable by Default
The closure API defaults to immutable (Fn) closures because they are more
likely to satisfy UnwindSafe automatically:
&TwhereT: RefUnwindSafeisUnwindSafe&mut Tis neverUnwindSaferegardless ofT
This means:
ScopedClosure::borrowcreates an immutableFnclosureScopedClosure::borrow_mutcreates a mutableFnMutclosure
Immutable closures can be upcasted to mutable closures using upcast_ref.
§Type Aliases
ScopedClosure<'a, T>— The unified closure type with a lifetime parameterClosure<T>— Alias forScopedClosure<'static, T>(for backwards compatibility)
§Unwind Safety
For immediate/synchronous callbacks, use &dyn FnMut / &dyn Fn, when you are
absolutely sure the code will support unwind safety.
For ScopedClosure, the default constructors (borrow, borrow_mut, own) catch
panics, while the _aborting variants (borrow_aborting, borrow_mut_aborting, etc.) do not.
§Ownership Model
ScopedClosure follows the same ownership model as other wasm-bindgen types:
the JavaScript reference remains valid until the Rust value is dropped. When
dropped, the closure is invalidated and any subsequent calls from JavaScript
will throw an exception.
For borrowed closures created with borrow/borrow_mut, Rust’s borrow checker
ensures the ScopedClosure cannot outlive the closure’s captured data.
See the ScopedClosure type documentation for detailed examples.
Structs§
- Scoped
Closure - A closure with a lifetime parameter that represents a Rust closure passed to JavaScript.
Type Aliases§
- Closure
- Alias for
ScopedClosure<'static, T>for backwards compatibility.