extends = 类

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


# #![allow(unused_variables)]
#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
#}

为以上代码块生成的 trait 实现是


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

可以多次为较长的继承链指定 extends = ... 属性,并且将为每个类型生成 AsRef 和类似的 impl。


# #![allow(unused_variables)]
#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();
#}