extends = 类
extends
属性可以用来声明一个导入的类型扩展(在 JS 类层次结构意义上)另一个类型。这将生成 AsRef
、AsMut
和 From
的 impl,用于在静态已知继承层次结构的情况下将一个类型转换为另一个类型
#![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
等 impl。
#![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(); }