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