使用wasm_bindgenwith serde,我尝试JsValue使用惯用的 rust 返回一个复杂的结构。我创建了一个单独的示例来说明我所看到的错误。
结构声明:
#[derive(Serialize)]
pub struct BookStoreData {
pub h: HashMap<String, String>,
pub name: String,
}
Run Code Online (Sandbox Code Playgroud)
函数定义:
#[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)
}
Run Code Online (Sandbox Code Playgroud)
我收到此编译错误:
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`
Run Code Online (Sandbox Code Playgroud)
您可以查看基于rust-parcel-template的完整示例
要重现错误,请从存储库的根目录运行npm run start或cd crate && cargo build
答案是作为评论提供的。 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)
}
Run Code Online (Sandbox Code Playgroud)
其次,什么是元组变体?
在这种情况下,有问题的行可能是一个函数或一个结构或枚举的元组变体(通过友好的 Rustacean 的推文):
元组可以在结构体或枚举中使用:
struct S(usize); // tuple-like struct
enum E {
T(usize), // tuple variant
}
Run Code Online (Sandbox Code Playgroud)
博客文章中有更多详细信息:什么是元组变体?
这个特别令人困惑的错误消息将来可能会得到改进。博客文章和随后的Twitter 讨论导致了此错误报告:https://github.com/rust-lang/rust/issues/65386
| 归档时间: |
|
| 查看次数: |
4682 次 |
| 最近记录: |