mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-15 22:11:23 +00:00
examples: Add an example of using duck-typed interfaces
This commit is contained in:
23
examples/duck-typed-interfaces/src/lib.rs
Executable file
23
examples/duck-typed-interfaces/src/lib.rs
Executable file
@ -0,0 +1,23 @@
|
||||
extern crate wasm_bindgen;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Here is a duck-typed interface for any JavaScript object that has a `quack`
|
||||
/// method.
|
||||
///
|
||||
/// Note that any attempts to check if an object is a `Quacks` with
|
||||
/// `JsCast::is_instance_of` (i.e. the `instanceof` operator) will fail because
|
||||
/// there is no JS class named `Quacks`.
|
||||
#[wasm_bindgen]
|
||||
extern {
|
||||
pub type Quacks;
|
||||
|
||||
#[wasm_bindgen(structural, method)]
|
||||
pub fn quack(this: &Quacks) -> String;
|
||||
}
|
||||
|
||||
/// Next, we can export a function that takes any object that quacks:
|
||||
#[wasm_bindgen]
|
||||
pub fn make_em_quack_to_this(duck: &Quacks) {
|
||||
let s = duck.quack();
|
||||
// ...
|
||||
}
|
Reference in New Issue
Block a user