extends = Class
extends
屬性可用於表示導入的類型擴展(在 JS 類別層次結構意義上)另一個類型。這將產生 AsRef
、AsMut
和 From
impls,用於在我們靜態知道繼承層次結構的情況下將一個類型轉換為另一個類型
#![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 }
為上述程式碼區塊生成的 trait 實作如下
#![allow(unused)] fn main() { impl From<Bar> for Foo { ... } impl AsRef<Foo> for Bar { ... } impl AsMut<Foo> for Bar { ... } }
extends = ...
屬性可以多次指定以用於更長的繼承鏈,並且會為每個類型生成 AsRef
和類似的 impls。
#![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(); }