Description
Motivation
To be able to use traits witn wasm-bindgen as an alternative to "Duck-Type Interface"s.
pub trait Quacks {
fn quack(&self) -> String;
}
#[wasm_bindgen]
pub fn make_em_quack_to_this(duck: impl Quacks) {
let _s = duck.quack();
}
Currently, this produces two errors:
#[wasm_bindgen] can only be applied to a function, struct, enum, impl, or extern block
I'd love to here move about traits and wasm-bindgen. I've looked through several issues such as rustwasm/rfcs#11 but seem to be missing some likely longer discussion.
the trait bound impl Quacks: wasm_bindgen::convert::traits::FromWasmAbi is not satisfied
Reading through https://docs.rs/wasm-bindgen/0.2.50/wasm_bindgen/convert/index.html it seems to as though implementing your own conversions is discouraged. It might be necessary to support traits like this but I am not sure.
I should note, is it possible to implement the various conversion traits for the example above? I'm wondering if it has been tried.
Proposed Solution
Enable the following example.
pub trait Quacks {
fn quack(&self) -> String;
}
#[wasm_bindgen]
pub fn make_em_quack_to_this(duck: impl Quacks) {
let _s = duck.quack();
}
The trait would generate a TypeScript interface called Quacks
as well as a JavaScript object. This will likely need to leverage Closure
.
Alternatives
Use the recommended "Duck-Typed Interface".
Additional Context
"Duck-Typed Interfaces" are defined in the docs as such:
#[wasm_bindgen]
extern "C" {
pub type Quacks;
#[wasm_bindgen(structural, method)]
pub fn quack(this: &Quacks) -> String;
}
#[wasm_bindgen]
pub fn make_em_quack_to_this(duck: &Quacks) {
let _s = duck.quack();
}