readonly
當附加到 pub
結構體欄位時,這表示它是從 JavaScript 中唯讀的,並且不會產生 setter 並導出到 JavaScript。
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen] pub fn make_foo() -> Foo { Foo { first: 10, second: 20, } } #[wasm_bindgen] pub struct Foo { pub first: u32, #[wasm_bindgen(readonly)] pub second: u32, } #}
在這裡,first
欄位將可在 JS 中讀寫,但 second
欄位將是 JS 中的 readonly
欄位,其中 setter 未實作,並且嘗試設定它將會拋出例外。
import { make_foo } from "./my_module";
const foo = make_foo();
// Can both get and set `first`.
foo.first = 99;
console.log(foo.first);
// Can only get `second`.
console.log(foo.second);