Struct ScopedClosure
pub struct ScopedClosure<'a, T: ?Sized> { /* private fields */ }
A closure with a lifetime parameter that represents a Rust closure passed to JavaScript.
ScopedClosure<'a, T> is the unified closure type. The lifetime 'a indicates
how long the closure is valid:
-
ScopedClosure<'static, T>- An owned closure with heap-allocated data. Requires'staticcaptures. Use for long-lived closures like event listeners and timers. Created withClosure::neworScopedClosure::own. May transfer ownership to the JS GC using finalizers. -
ScopedClosure<'a, T>(non-'static) - A borrowed closure referencing stack data. Allows non-'staticcaptures. Use for immediate/synchronous callbacks. Created withScopedClosure::borrow(forFnMut) orScopedClosure::borrow_immutable(forFn). Cannot transfer ownership to JS GC.
[Closure<T>] is currently a type alias for ScopedClosure<'static, T>. In
a future release, a lifetime argument will be added to this alias.
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: "closure invoked recursively or after being dropped".
For 'static closures, you can also:
- Pass by value to transfer ownership to JS (implements
IntoWasmAbi) - Call
forget()to leak the closure (JS can use it indefinitely) - Call
into_js_value()to transfer to JS GC management
Lifetime Safety
For borrowed closures, Rust's borrow checker ensures that ScopedClosure cannot
be held longer than the closure's captured data:
let mut sum = 0;
let mut f = |x: u32| { sum += x; }; // f borrows sum
let closure = ScopedClosure::borrow(&mut f); // closure borrows f
// closure cannot outlive f, and f cannot outlive sum
Examples
Borrowed closures with ScopedClosure::borrow
Use for immediate/synchronous callbacks where JS calls the closure right away:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn call_immediately(cb: &ScopedClosure<dyn FnMut(u32)>);
}
let mut sum = 0;
{
let mut f = |x: u32| { sum += x; };
let closure = ScopedClosure::borrow(&mut f);
call_immediately(&closure);
} // closure dropped here, JS function invalidated
assert_eq!(sum, 42);
Owned closures with Closure::new
Use for long-lived callbacks like event listeners and timers:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn setInterval(closure: &Closure<dyn FnMut()>, time: u32) -> i32;
}
// Closure::new requires 'static, so use `move` to capture by value
let cb = Closure::new(move || {
// ...
});
setInterval(&cb, 1000);
// Must keep `cb` alive or call `cb.forget()` to transfer to JS
Transferring ownership to JS
Pass a ScopedClosure<'static, T> by value to transfer ownership:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn set_one_shot_callback(cb: ScopedClosure<dyn FnMut()>);
}
let cb = ScopedClosure::own(|| { /* ... */ });
set_one_shot_callback(cb); // Ownership transferred, no need to store
Implementations
impl<'a, T> ScopedClosure<'a, T>
where
T: ?Sized + WasmClosure,
fn as_js_value(&self) -> &JsValueObtain a
&JsValuereference for this closure
impl<T> ScopedClosure<'static, T>
where
T: ?Sized + WasmClosure,
fn new<F>(t: F) -> Self where F: IntoWasmClosure<T> + MaybeUnwindSafe + 'static,Alias for
Closure::own.Creates a new static owned
ScopedClosure<'static, T>from the provided Rust function, with panic unwind support.The type parameter
Tdetermines whether the closure isFnorFnMut.Supports unwind via its UnwindSafe bound when building with panic=unwind. Alternatively, pass
Closure::own(AssertUnwindSafe(...))to assert unwind safety, or useown_assert_unwind_safeorown_aborting.When provided to a JS function as an own value, to be managed by the JS GC.
See
borrowfor creating a borrowedScopedClosurewith an associated lifetime (defaults to immutableFn).fn own<F>(t: F) -> Self where F: IntoWasmClosure<T> + MaybeUnwindSafe + 'static,Creates a new static owned
ScopedClosure<'static, T>from the provided Rust function, with panic unwind support.The type parameter
Tdetermines whether the closure isFnorFnMut.Supports unwind via its UnwindSafe bound when building with panic=unwind. Alternatively, pass
Closure::own(AssertUnwindSafe(...))to assert unwind safety, or useown_assert_unwind_safeorown_aborting.When provided to a JS function as an own value, to be managed by the JS GC.
See
borrowfor creating a borrowedScopedClosurewith an associated lifetime (defaults to immutableFn).fn own_aborting<F>(t: F) -> Self where F: IntoWasmClosure<T> + 'static,Creates a new owned
'staticclosure that aborts on panic.Unlike
own, this version does NOT catch panics and does NOT requireUnwindSafe. If the closure panics, the process will abort.The type parameter
Tdetermines whether the closure isFnorFnMut.When provided to a JS function as an own value, to be managed by the JS GC.
See
borrow_abortingfor creating a borrowedScopedClosurewith an associated lifetime.Note: Not unwind safe. Prefer
ownorownwithAssertUnwindSafewhen possible.fn own_assert_unwind_safe<F>(t: F) -> Self where F: IntoWasmClosure<T> + 'static,Creates a new static owned
ScopedClosure<'static, T>from the provided Rust function, with panic unwind support.The type parameter
Tdetermines whether the closure isFnorFnMut.When provided to a JS function as an own value, to be managed by the JS GC.
Safety: Unwind safety is assumed when using this function, like using
AssertUnwindSafe(...), this must be verified explicitly.See
borrow_abortingfor creating a borrowedScopedClosurewith an associated lifetime.fn wrap<F>(data: Box<F>) -> Self where F: IntoWasmClosure<T> + ?Sized + MaybeUnwindSafe,A more direct version of
Closure::newwhich creates aClosurefrom aBox<dyn Fn>/Box<dyn FnMut>, which is how it's kept internally.Supports unwind via its UnwindSafe bound when building with panic=unwind. Alternatively, use
wrap_assert_unwind_safeto assert unwind safety, or usewrap_aborting.fn wrap_aborting<F>(data: Box<F>) -> Self where F: IntoWasmClosure<T> + ?Sized,A more direct version of
Closure::newwhich creates aClosurefrom aBox<dyn Fn>/Box<dyn FnMut>, which is how it's kept internally.This version aborts on panics.
fn wrap_assert_unwind_safe<F>(data: Box<F>) -> Self where F: IntoWasmClosure<T> + ?Sized,A more direct version of
Closure::newwhich creates aClosurefrom aBox<dyn Fn>/Box<dyn FnMut>, which is how it's kept internally.Safety: Unwind safety is assumed when using this function, like using
AssertUnwindSafe(...), this must be verified explicitly.This version catches panics when unwinding is available.
fn borrow<'a, F>(t: &'a F) -> ScopedClosure<'a, T::Static> where F: IntoWasmClosureRef<T> + MaybeUnwindSafe + ?Sized,Creates a scoped closure by borrowing an immutable
Fnclosure with panic unwind support.This is the recommended way to pass closures to JavaScript for immediate/ synchronous use. Unlike
Closure::own, this does not require the closure to be'static, allowing you to capture references to local variables.Use
borrow_mutwhen you need to mutate captured state.The returned
ScopedClosure<'a, _>has lifetime'afrom the closure reference, which means it cannot outlive the closure or any data the closure captures.Supports unwind via its UnwindSafe bound when building with panic=unwind. Wrap with
AssertUnwindSafeif necessary to achieve this bound, or useborrow_assert_unwind_safeorborrow_abortingfor non-unwind-safe functions.The resulting closure can be upcasted to
FnMutusingupcast_ref.When to use scoped closures
Use
ScopedClosure::borroworScopedClosure::borrow_mutwhen:- JavaScript will call the closure immediately and not retain it
- You need to capture non-
'staticreferences - You want automatic cleanup when the
ScopedClosureis dropped
Closure lifetime
The JavaScript function is only valid while the
ScopedClosureexists. Once dropped, the JavaScript function is invalidated. If JavaScript retains a reference and calls it later, it will throw: "closure invoked recursively or after being dropped".Rust's borrow checker ensures
ScopedClosurecannot outlive the closure's captured data, preventing use-after-free bugs.Example
use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn call_with_value(cb: &ScopedClosure<dyn Fn(u32)>, value: u32); fn call_fnmut(cb: &ScopedClosure<dyn FnMut(u32)>, value: u32); } let data = vec![1, 2, 3]; let f = |x| { println!("data len: {}, x: {}", data.len(), x); }; let closure = ScopedClosure::borrow(&f); call_with_value(&closure, 42); // Can also upcast to FnMut call_fnmut(closure.upcast_ref(), 42);fn borrow_aborting<'a, F>(t: &'a F) -> ScopedClosure<'a, T::Static> where F: IntoWasmClosureRef<T> + ?Sized,Like
borrow, but does not catch panics.If the closure panics, the process will abort. This variant does not require
UnwindSafe.Note: Not unwind safe. Prefer
borroworborrow_assert_unwind_safewhen possible.fn borrow_assert_unwind_safe<'a, F>(t: &'a F) -> ScopedClosure<'a, T::Static> where F: IntoWasmClosureRef<T> + ?Sized,Like
borrow, but catches panics without requiringMaybeUnwindSafe.Safety: Unwind safety is assumed when using this function, like using
AssertUnwindSafe(...), this must be verified explicitly.fn borrow_mut<'a, F>(t: &'a mut F) -> ScopedClosure<'a, T::Static> where F: IntoWasmClosureRefMut<T> + MaybeUnwindSafe + ?Sized,Creates a scoped closure by mutably borrowing a
FnMutclosure.Use this for closures that need to mutate captured state. For closures that don't need mutation, prefer
borrowwhich creates an immutableFnclosure that is more likely to satisfyUnwindSafeautomatically.Supports unwind via its UnwindSafe bound when building with panic=unwind. Wrap with
AssertUnwindSafeif necessary to achieve this bound, or useborrow_mut_assert_unwind_safeorborrow_mut_abortingfor non-unwind-safe functions.See
borrowfor full documentation on scoped closures.Example
use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn call_three_times(cb: &ScopedClosure<dyn FnMut(u32)>); } let mut sum = 0; let closure = ScopedClosure::borrow_mut(&mut |x: u32| { sum += x; }); call_three_times(&closure); // closure dropped, `sum` is accessible again assert_eq!(sum, 6); // 1 + 2 + 3fn borrow_mut_aborting<'a, F>(t: &'a mut F) -> ScopedClosure<'a, T::Static> where F: IntoWasmClosureRefMut<T> + ?Sized,Like
borrow_mut, but does not catch panics.If the closure panics, the process will abort. This variant does not require
UnwindSafe.Note: Not unwind safe. Prefer
borrow_mutorborrow_mut_assert_unwind_safewhen possible.fn borrow_mut_assert_unwind_safe<'a, F>(t: &'a mut F) -> ScopedClosure<'a, T::Static> where F: IntoWasmClosureRefMut<T> + ?Sized,Like
borrow_mut, but catches panics without requiringMaybeUnwindSafe.Safety: Unwind safety is assumed when using this function, like using
AssertUnwindSafe(...), this must be verified explicitly.fn into_js_value(self) -> JsValueRelease memory management of this closure from Rust to the JS GC.
When a
Closureis dropped it will release the Rust memory and invalidate the associated JS closure, but this isn't always desired. Some callbacks are alive for the entire duration of the program or for a lifetime dynamically managed by the JS GC. This function can be used to drop thisClosurewhile keeping the associated JS function still valid.If the platform supports weak references, the Rust memory will be reclaimed when the JS closure is GC'd. If weak references is not supported, this can be dangerous if this function is called many times in an application because the memory leak will overwhelm the page quickly and crash the wasm.
Safety Note
This method is only available on
'staticclosures. Calling it on a borrowedScopedClosurewould be unsound because the closure data would become invalid when the borrow ends.fn forget(self)Same as
mem::forget(self).This can be used to fully relinquish closure ownership to the JS.
Safety Note
This method is only available on
'staticclosures. Calling it on a borrowedScopedClosurewould be unsound because the closure data would become invalid when the borrow ends.fn once<F, A, R>(fn_once: F) -> Self where F: WasmClosureFnOnce<T, A, R> + MaybeUnwindSafe,Create a
Closurefrom a function that can only be called once.Since we have no way of enforcing that JS cannot attempt to call this
FnOne(A...) -> Rmore than once, this produces aClosure<dyn FnMut(A...) -> R>that will dynamically throw a JavaScript error if called more than once.Example
use wasm_bindgen::prelude::*; // Create an non-`Copy`, owned `String`. let mut s = String::from("Hello"); // Close over `s`. Since `f` returns `s`, it is `FnOnce` and can only be // called once. If it was called a second time, it wouldn't have any `s` // to work with anymore! let f = move || { s += ", World!"; s }; // Create a `Closure` from `f`. Note that the `Closure`'s type parameter // is `FnMut`, even though `f` is `FnOnce`. let closure: Closure<dyn FnMut() -> String> = Closure::once(f);Note: the
AandRtype parameters are here just for backward compat and will be removed in the future.fn once_aborting<F, A, R>(fn_once: F) -> Self where F: WasmClosureFnOnceAbort<T, A, R>,Create a
Closurefrom a function that can only be called once.Unlike
once, this version does NOT catch panics and does NOT requireUnwindSafe. If the closure panics, the process will abort.Use this when:
- Your closure captures types that aren't
UnwindSafe(likeRc<Cell<T>>) - You don't need panic catching across the JS boundary
- You prefer abort-on-panic behavior
Since we have no way of enforcing that JS cannot attempt to call this
FnOnce(A...) -> Rmore than once, this produces aClosure<dyn FnMut(A...) -> R>that will dynamically throw a JavaScript error if called more than once.Note: Not unwind safe. Prefer
onceoroncewithAssertUnwindSafewhen possible.Note: the
AandRtype parameters are here just for backward compat and will be removed in the future.- Your closure captures types that aren't
fn once_assert_unwind_safe<F, A, R>(fn_once: F) -> Self where F: WasmClosureFnOnceAbort<T, A, R>,Create a
Closurefrom a function that can only be called once, with panic unwind support.Safety: Unwind safety is assumed when using this function, like using
AssertUnwindSafe(...), this must be verified explicitly.Use this when:
- Your closure captures types that aren't
UnwindSafe(likeRc<Cell<T>>) - You still want panics to be caught and converted to JS exceptions
Since we have no way of enforcing that JS cannot attempt to call this
FnOnce(A...) -> Rmore than once, this produces aClosure<dyn FnMut(A...) -> R>that will dynamically throw a JavaScript error if called more than once.Note: the
AandRtype parameters are here just for backward compat and will be removed in the future.- Your closure captures types that aren't
fn once_into_js<F, A, R>(fn_once: F) -> JsValue where F: WasmClosureFnOnce<T, A, R> + MaybeUnwindSafe,Convert a
FnOnce(A...) -> Rinto a JavaScriptFunctionobject.If the JavaScript function is invoked more than once, it will throw an exception.
Unlike
Closure::once, this does not return aClosurethat can be dropped before the function is invoked to deallocate the closure. The only way theFnOnceis deallocated is by calling the JavaScript function. If the JavaScript function is never called then theFnOnceand everything it closes over will leak.use wasm_bindgen::{prelude::*, JsCast}; let f = Closure::once_into_js(move || { // ... }); assert!(f.is_instance_of::<js_sys::Function>());Note: the
AandRtype parameters are here just for backward compat and will be removed in the future.
Trait Implementations
impl<'a: 'b, 'b, T1, T2> UpcastFrom<ScopedClosure<'a, T1>> for ScopedClosure<'b, T2>
where
T1: ?Sized + WasmClosure,
T2: ?Sized + WasmClosure + UpcastFrom<T1>,
impl<T> Debug for ScopedClosure<'_, T>
where
T: ?Sized,
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl<T> IntoWasmAbi for ScopedClosure<'static, T>
where
T: WasmClosure + ?Sized,
type Abi = u32;fn into_abi(self) -> u32
impl<T> OptionIntoWasmAbi for ScopedClosure<'static, T>
where
T: WasmClosure + ?Sized,
fn none() -> Self::Abi
impl<T: ?Sized> AsRef<JsValue> for ScopedClosure<'_, T>
fn as_ref(&self) -> &JsValue
impl<T: ?Sized> Drop for ScopedClosure<'_, T>
fn drop(&mut self)