Search code examples
rustwebassemblywasm-bindgen

How to access JS object properties in Wasm (Rust)?


I'm using wasm bindgen and I have following function :

#[wasm_bindgen]
pub fn obj(o: &JsValue){
console::log_1(o);
}

and in js I call this function obj({name: "john"}); and it works fine, but when i try to console::log_1(o.name); it gives error unknown field pointing at name


Solution

  • JsValue does not have a field name. To get this field you have to declare the JS object.

    Variant 1

    Add serde to your dependencies:

    serde = "^1.0.101"
    serde_derive = "^1.0.101"
    

    Rust code:

    extern crate serde;
    
    #[derive(Serialize, Deserialize)]
    pub struct User {
        pub name: String,
    }
    
    #[wasm_bindgen]
    pub fn obj(o: &JsValue){
        let user: User = o.into_serde().unwrap();
        console::log_1(user.name);
    }
    

    Variant 2

    Another way is to use wasm-bindgen directly but I never used it. It should work like this I think:

    #[wasm_bindgen]
    pub struct User {
        pub name: String,
    }
    
    #[wasm_bindgen]
    pub fn obj(o: User){
        console::log_1(o.name);
    }