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_count
是 usize
类型,这里我将画布所有格子视作一个从左到右,从上到下的一维数组,这个方法的作用就是将数组索引映射成 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)
如何解决这个错误?
已解决,
wasm-bindgen
不支持元组。可以使用元组结构体代替。详见:How to return a tuple to frontend from wasm?