Home > Back-end >  How to use exported struct in JS file?
How to use exported struct in JS file?

Time:10-24

I have the following definitions in the Rust code:

#[wasm_bindgen]
pub struct Point {
    x: i32,
    y: i32,
}

#[wasm_bindgen]
impl Point {
    #[wasm_bindgen(constructor)]
    pub fn new(x: i32, y: i32) -> Point {
        Point { x, y }
    }
}

I logged the created object in JS file:

let p = new Point(23, 34);
console.log(p);

But it's giving me a pointer value with prototype, I don't know how to use it.

enter image description here

How can I get JS object like { x: 23, y: 34 } with prototype?

CodePudding user response:

By default, wasm_bindgen doesn't include the actual fields of structs when passing them to JS, instead generating a wrapper object that simply has a pointer to the data on the (WASM) heap and exposes the methods/properties using the prototype. You should be able to access (public) fields and invoke methods using standard JS syntax, as shown here in the wasm-bindgen reference.

If you really want to pass the actual contents back, you can use JsValue::from_serde, which allows serializing any type that implements Serialize into a JS object. Note that this object will not expose the methods, however - it's intended for passing plain data across the JS/WASM boundary. This is documented here in the wasm-bindgen reference.

  • Related