examples: Add an example of using duck-typed interfaces

This commit is contained in:
Nick Fitzgerald
2018-09-11 16:29:25 -07:00
parent 27a7008764
commit a311c29f1d
11 changed files with 121 additions and 0 deletions

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