首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rust wasm-带字符串的bindgen结构

Rust wasm-带字符串的bindgen结构
EN

Stack Overflow用户
提问于 2021-07-04 18:48:18
回答 1查看 311关注 0票数 1

我正在尝试导出以下结构:

代码语言:javascript
复制
#[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,
}

但是我得到了:

代码语言:javascript
复制
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`

以及:

代码语言:javascript
复制
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

我是个生锈新手,所以非常感谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-04 23:01:52

根据wasm-bindgen#1985的说法,为了让自动生成的访问器正常工作,结构的公共字段必须为Copy

您可以将字段设置为私有,或者使用#[wasm_bindgen(skip)]对其进行注释,然后直接实现getter和setter。

在wasm-bindgen的文档中有一个example provided,描述了如何编写这些代码:

代码语言:javascript
复制
#[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中拥有相同的行为,并能够控制锈面上正在设置的内容。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68243940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档