gpt4 book ai didi

rust - 什么是元组变体? (了解编译器错误信息)

转载 作者:行者123 更新时间:2023-11-29 08:26:32 24 4
gpt4 key购买 nike

wasm_bindgenserde 结合使用,我试图为使用惯用 Rust 的复杂结构返回一个 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

最佳答案

答案是作为评论提供的。 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)

}

其次,什么是元组变体?

在这种情况下,有问题的行可以是结构或枚举的函数或元组变体(来自友好的 Rustacean 的 tweet):

元组可以用在结构或枚举中:

struct S(usize); // tuple-like struct
enum E {
T(usize), // tuple variant
}

博文中有更多详细信息:What's a tuple variant?

这个特别令人困惑的错误消息可能会在未来得到改进。博文及后续 twitter discussion导致此错误报告:https://github.com/rust-lang/rust/issues/65386

关于rust - 什么是元组变体? (了解编译器错误信息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com