如何使用wasm_bindgen返回带有JsValue的结果?

问题描述 投票:0回答:1

使用wasm_bindgenserde,我试图使用惯用生锈返回JsValue的复杂结构。我创建了一个孤立的例子来说明我所看到的错误。

结构声明:

#[derive(Serialize)]
pub struct BookStoreData {
    pub h: HashMap<String, String>,
    pub name: String,
}

功能定义:

#[wasm_bindgen]
pub fn hello_hash(count: i32) -> Result<JsValue, JsValue> {
    set_panic_hook();
    let mut book_reviews = HashMap::new();

    book_reviews.insert(
        "Grimms' Fairy Tales".to_string(),
        "Masterpiece.".to_string(),
    );
    let data = BookStoreData {
        h: book_reviews,
        name: "My Book Store".to_string(),
    };

    let js_result: JsValue = JsValue::from_serde(&data).unwrap();

    OK(js_result)    

}

我得到这个编译错误:

error[E0425]: cannot find function `OK` in this scope
  --> src/hello_whatever.rs:46:5
   |
46 |     OK(js_result)    
   |     ^^ help: a tuple variant with a similar name exists: `Ok`

你可以看一下full example基于rust-parcel-template

要从repo的根目录重现错误,请运行npm run startcd crate && cargo build

rust wasm-bindgen
1个回答
1
投票

答案是作为评论提供的。 Ok拼写为小写的k

我测试了它,下面是一个小改动的工作代码:

#[wasm_bindgen]
pub fn hello_hash(count: i32) -> Result<JsValue, JsValue> {
    set_panic_hook();
    let mut book_reviews = HashMap::new();

    book_reviews.insert(
        "Grimms' Fairy Tales".to_string(),
        "Masterpiece.".to_string(),
    );
    let data = BookStoreData {
        h: book_reviews,
        name: "My Book Store".to_string(),
    };

    let js_result: JsValue = JsValue::from_serde(&data).unwrap();

    Ok(js_result)    

}
© www.soinside.com 2019 - 2024. All rights reserved.