-
SummaryCan I export a multi-level Rust struct to JavaScript and then interact with it by setting/changing different properties? I have a configuration object arranged hierarchically. Would like to preserve that hierarchy when bridging JavaScript with WebAssembly. Below is a snippet that compiles. From JavaScript I can only read and set public properties (e.g., Please note, I am aware of using The only solution I can think of right now is to flatten my configs to have just a root level. Before I go in that direction was curious to see if it is possible to preserve the nesting. pub struct AxisConfigs {
pub arrowWidth: f64,
pub arrowHeight: f64
}
#[wasm_bindgen]
pub struct GraphConfigs {
pub width: f64,
pub height: f64,
xAxis: AxisConfigs,
yAxis: AxisConfigs
}
#[wasm_bindgen]
impl GraphConfigs {
pub fn new() -> Self {
Self {
width: 250.0,
height: 250.0,
xAxis: AxisConfigs {
arrowWidth: 9.0,
arrowHeight: 6.0
},
yAxis: AxisConfigs {
arrowWidth: 9.0,
arrowHeight: 6.0
}
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
It should work if you also export use wasm_bindgen::prelude::*;
#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct AxisConfigs {
pub arrowWidth: f64,
pub arrowHeight: f64,
}
#[wasm_bindgen]
pub struct GraphConfigs {
pub width: f64,
pub height: f64,
pub xAxis: AxisConfigs,
pub yAxis: AxisConfigs,
}
#[wasm_bindgen]
impl GraphConfigs {
pub fn new() -> Self {
Self {
width: 250.0,
height: 250.0,
xAxis: AxisConfigs {
arrowWidth: 9.0,
arrowHeight: 6.0,
},
yAxis: AxisConfigs {
arrowWidth: 9.0,
arrowHeight: 6.0,
},
}
}
} That does clutter things up a bit with an extra export that should never be used, though. |
Beta Was this translation helpful? Give feedback.
-
Thank you for the suggestion. It does compile, but, unfortunately, it won't work for me. Copying is the issue. I would like for the instantiated nested structs to be treated in the same way as the top-level object (i.e., |
Beta Was this translation helpful? Give feedback.
-
What I wound up doing is splitting my deeply nested configuration into three flat rust structures and then exporting them to JavaScript. Not as unified as having one struct, but workable enough. It would be nice to have a multi-level struct whose nested structs can be accessed without data being copied. If we can do that with the root struct, then it can be done with the nested structs also. |
Beta Was this translation helpful? Give feedback.
What I wound up doing is splitting my deeply nested configuration into three flat rust structures and then exporting them to JavaScript. Not as unified as having one struct, but workable enough. It would be nice to have a multi-level struct whose nested structs can be accessed without data being copied. If we can do that with the root struct, then it can be done with the nested structs also.