Search code examples
rustwebassemblywasm-bindgen

What is the difference between Closure::new and Closure::wrap in Rust wasm


What is the difference between Closure::new and Closure::wrap?

Both are used to create closure but I wanna know when to use these functions.


Solution

  • It's quite simple, all that Closure::new does is put the closure in a Box , unsize it and delegate to wrap as you can see by looking at the code:

        pub fn new<F>(t: F) -> Closure<T>
        where
            F: IntoWasmClosure<T> + 'static,
        {
            Closure::wrap(Box::new(t).unsize())
        }
    

    So use Closure::new when you have a bare Rust closure or function and use wrap when your closure is already a trait object contained in a Box (Box<dyn Fn> or Box<dyn FnMut>) as new would wrap it in an additional Box and thus create unnecessary indirection.