3

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

1
  • The error with unknown field occurs when compiling or at runtime? Commented Jan 10, 2020 at 9:49

2 Answers 2

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

4

There is a third variant: Use js_sys::Reflect::get.

In your case it would look like this:

let value = js_sys::Reflect::get(o, &"name".into())?;
console::log_1(value);

Please check the wasm_bindgen docs for Accessing Properties of Untyped JavaScript Values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.