1
1
# ` getter ` and ` setter `
2
2
3
- It is also possible to interact with ` Rust ` types either by using fields accessors. For example, the following:
3
+ The ` getter ` and ` setter ` attributes can be used in Rust ` impl ` blocks to define
4
+ properties in JS that act like getters and setters of a field. For example:
4
5
5
6
``` rust
6
7
#[wasm_bindgen]
7
- extern " C" {
8
- fn check_modify_and_return_baz_in_js_fields (baz : Baz ) -> Baz ;
9
- }
10
-
11
- #[wasm_bindgen_test]
12
- fn create_and_check_baz_in_rust () {
13
- let baz = check_modify_and_return_baz_in_js_fields (Baz { field : 123 });
14
- assert_eq! (baz . field. unwrap (), 456 );
15
- }
16
-
17
- #[wasm_bindgen]
18
- #[derive(Default )]
19
8
pub struct Baz {
20
9
field : i32 ,
21
10
}
22
11
23
12
#[wasm_bindgen]
24
13
impl Baz {
14
+ #[wasm_bindgen(constructor)]
15
+ pub fn new (field : i32 ) -> Baz {
16
+ Baz { field }
17
+ }
18
+
25
19
#[wasm_bindgen(getter)]
26
20
pub fn field (& self ) -> i32 {
27
21
self . field
28
22
}
29
23
30
- #[wasm_bindgen(setter = field )]
24
+ #[wasm_bindgen(setter)]
31
25
pub fn set_field (& mut self , field : i32 ) {
32
26
self . field = field ;
33
27
}
@@ -37,9 +31,34 @@ impl Baz {
37
31
Can be combined in ` JavaScript ` like in this snippet:
38
32
39
33
``` js
40
- check_modify_and_return_baz_in_js_fields = (baz ) => {
41
- console .log (baz .field , 123 );
42
- baz .field = 456 ;
43
- return baz;
44
- };
45
- ```
34
+ const obj = new Baz (3 );
35
+ assert .equal (obj .field , 3 );
36
+ obj .field = 4 ;
37
+ assert .equal (obj .field , 4 );
38
+ ```
39
+
40
+ You can also configure the name of the property that is exported in JS like so:
41
+
42
+ ``` rust
43
+ #[wasm_bindgen]
44
+ impl Baz {
45
+ #[wasm_bindgen(getter = anotherName)]
46
+ pub fn field (& self ) -> i32 {
47
+ self . field
48
+ }
49
+
50
+ #[wasm_bindgen(setter = anotherName)]
51
+ pub fn set_field (& mut self , field : i32 ) {
52
+ self . field = field ;
53
+ }
54
+ }
55
+ ```
56
+
57
+ Getters are expected to take no arguments other than ` &self ` and return the
58
+ field's type. Setters are expected to take one argument other than ` &mut self `
59
+ (or ` &self ` ) and return no values.
60
+
61
+ The name for a ` getter ` is by default inferred from the function name it's
62
+ attached to. The default name for a ` setter ` is the function's name minus the
63
+ ` set_ ` prefix, and if ` set_ ` isn't a prefix of the function it's an error to not
64
+ provide the name explicitly.
0 commit comments