extends = 类

extends 属性可用于表示导入的类型扩展(在 JS 类层次结构意义上)另一个类型。这将为将类型转换为另一个类型生成 AsRefAsMutFrom 实现,前提是我们静态地知道继承层次结构

#![allow(unused)]
fn main() {
#[wasm_bindgen]
extern "C" {
    type Foo;

    #[wasm_bindgen(extends = Foo)]
    type Bar;
}

let x: &Bar = ...;
let y: &Foo = x.as_ref(); // zero cost cast
}

为上述代码块生成的特征实现为

#![allow(unused)]
fn main() {
impl From<Bar> for Foo { ... }
impl AsRef<Foo> for Bar { ... }
impl AsMut<Foo> for Bar { ... }
}

extends = ... 属性可以多次指定以用于更长的继承链,并且将为每个类型生成 AsRef 等实现。

#![allow(unused)]
fn main() {
#[wasm_bindgen]
extern "C" {
    type Foo;

    #[wasm_bindgen(extends = Foo)]
    type Bar;

    #[wasm_bindgen(extends = Foo, extends = Bar)]
    type Baz;
}

let x: &Baz = ...;
let y1: &Bar = x.as_ref();
let y2: &Foo = y1.as_ref();
}