Skip to content

Express "Duck-Typed Interface" as trait #1771

Closed
@garrettmaring

Description

@garrettmaring

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:

  1. #[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.

  1. 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();
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions