我正在尝试导出以下结构:
#[wasm_bindgen]
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum TokenType {
KeywordLiteral,
NumberLiteral,
Operator,
Separator,
StringLiteral,
}
#[wasm_bindgen]
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Token {
pub typ: TokenType,
pub val: String,
}但是我得到了:
error[E0277]: the trait bound `token::TokenType: std::marker::Copy` is not satisfied
--> src\tokenizer\token.rs:17:14
|
14 | #[wasm_bindgen]
| --------------- required by this bound in `__wbg_get_token_typ::assert_copy`
...
17 | pub typ: TokenType,
| ^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `token::TokenType`以及:
error[E0277]: the trait bound `std::string::String: std::marker::Copy` is not satisfied
--> src\tokenizer\token.rs:18:14
|
14 | #[wasm_bindgen]
| --------------- required by this bound in `__wbg_get_token_val::assert_copy`
...
18 | pub val: String,我可以将#[derive(Copy)]添加到TokenType,但不能添加到String。
我是个生锈新手,所以非常感谢你的帮助。
发布于 2021-07-04 23:01:52
根据wasm-bindgen#1985的说法,为了让自动生成的访问器正常工作,结构的公共字段必须为Copy。
您可以将字段设置为私有,或者使用#[wasm_bindgen(skip)]对其进行注释,然后直接实现getter和setter。
在wasm-bindgen的文档中有一个example provided,描述了如何编写这些代码:
#[wasm_bindgen]
pub struct Baz {
field: i32,
}
#[wasm_bindgen]
impl Baz {
#[wasm_bindgen(constructor)]
pub fn new(field: i32) -> Baz {
Baz { field }
}
#[wasm_bindgen(getter)]
pub fn field(&self) -> i32 {
self.field
}
#[wasm_bindgen(setter)]
pub fn set_field(&mut self, field: i32) {
self.field = field;
}
}当在wasm和js之间共享对象时,js对象只包含指向wasm运行时内存中的struct的指针。当您从JS访问字段时,它会经过一个已定义的属性,该属性会对wasm代码进行函数调用,要求它提供属性值(您可以将wasm内存看作一个位UInt8Array)。
要求对象为Copy可能是为了避免在自动生成这些getter和setter时出现意外。如果您手动实现它们,您可以在JS中拥有相同的行为,并能够控制锈面上正在设置的内容。
https://stackoverflow.com/questions/68243940
复制相似问题