I'm looking to create a function like this:
fn set_js_closure <T>(my_fn: T) -> Closure {
let my_fn_boxed = Box::new(my_fn);
Closure::wrap(my_fn_boxed) // or Closure::once if FnOnce
}
To use like this:
let cb = move || () /* varying closures */;
let cb_closure = set_js_closure(cb);
let cb_ref = cb_closure.as_ref().unchecked_ref();
// do stuff with closure
// do stuff with reference
I tried by using a function, and by using a struct+trait+impl combo, but anything I write breaks (even with generics) because the [traits/args/return-values/lifetimes] never match-up/apply for ALL the various closures that I pass.
Example attempts:
test v7 does not compile
test v8 compiles with generics but was unable to reuse the code with wasm::Closure methods.
test v9 does not compile because I cant use generics with "Box as"
I know I can just nest the box/closure statements (instead of using a function), or possibly create a macro to expand to all the different closure variants (suggested in IRC). But it's been bugging me for weeks that I'm unable to create a wrapper function for two statements.
What's the way to go about writing a wrapper function for unboxed closures? Thanks!
// Reference: closures I'm trying to pass:
//
// use wasm_bindgen::prelude::*;
// use web_sys::Event;
// function A
// with arg + return value
let cb = move |e: Event| -> Option<String> { /**/ };
let cb_boxed = Box::new(cb) as Box<dyn Fn(Event) -> Option<String>>;
// function B
// with arg
let cb = move |e: Event| { /**/ };
let cb_boxed = Box::new(cb) as Box<dyn FnMut(Event)>;
// function C
// as FnMut
let cb_1 = move || { /**/ };
let cb_1_boxed = Box::new(cb_1) as Box<dyn FnMut()>;
// as FnMut
let cb_2 = move || { /**/ };
let cb_2_boxed = Box::new(cb_2) as Box<dyn FnMut()>;
// as FnOnce + Closure::once + static
// calls: cb_1_closure, cb_2_closure
let cb_3 = move || { /**/ };
let cb_3_boxed = Box::new(cb_3) as Box<dyn FnOnce()>;