WebAssembly 如何向前端返回一个元组类型?

作者站长头像
站长
· 阅读数 8

Rust 代码:

#[wasm_bindgen]
impl CanvasData {
    pub fn index_to_coordinate(&self, index: usize) -> (usize, usize) {
      (index % self.cell_count, index / self.cell_count)
    }
}

CanvasData 是一个保存画布大小的结构体,cell_countusize 类型,这里我将画布所有格子视作一个从左到右,从上到下的一维数组,这个方法的作用就是将数组索引映射成 x, y 坐标。我想返回一个元组,然后在前端这样调用:

const [x, y] = canvasData.index_to_coordinate(100)

不过打包的时候遇到了报错:

wasm-pack build -t web
error[E0277]: the trait bound `(usize, usize): IntoWasmAbi` is not satisfied
[0]   --> src\lib.rs:16:1
[0]    |
[0] 16 | #[wasm_bindgen]
[0]    | ^^^^^^^^^^^^^^^ the trait `IntoWasmAbi` is not implemented for `(usize, usize)`
[0]    |
[0]    = help: the trait `IntoWasmAbi` is implemented for `()`
[0]    = note: required because of the requirements on the impl of `ReturnWasmAbi` for `(usize, usize)`
[0]    = note: this error originates in the attribute macro `wasm_bindgen::prelude::__wasm_bindgen_class_marker` (in Nightly builds, run with -Z macro-backtrace for more info)

如何解决这个错误?

回复
1个回答
avatar
test
2024-07-12

已解决,wasm-bindgen 不支持元组。可以使用元组结构体代替。

详见:How to return a tuple to frontend from wasm?

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容