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

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)

如何解决这个错误?

阅读 2.1k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题