5

我想编译以下代码。

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Dummy {}

#[wasm_bindgen]
pub fn test() -> Vec<Dummy> {
    vec![]
}

但是,编译器不允许我这样做。

error[E0277]: the trait bound `std::boxed::Box<[Dummy]>: wasm_bindgen::convert::traits::IntoWasmAbi` is not satisfied
  --> xxxx
   |
XX | #[wasm_bindgen]
   | ^^^^^^^^^^^^^^^ the trait `wasm_bindgen::convert::traits::IntoWasmAbi` is not implemented for `std::boxed::Box<[Dummy]>`
   |
   = help: the following implementations were found:
             <std::boxed::Box<[f32]> as wasm_bindgen::convert::traits::IntoWasmAbi>
             <std::boxed::Box<[f64]> as wasm_bindgen::convert::traits::IntoWasmAbi>
             <std::boxed::Box<[i16]> as wasm_bindgen::convert::traits::IntoWasmAbi>
             <std::boxed::Box<[i32]> as wasm_bindgen::convert::traits::IntoWasmAbi>
           and 9 others
   = note: required because of the requirements on the impl of `wasm_bindgen::convert::traits::IntoWasmAbi` for `std::vec::Vec<Dummy>`

我正在使用最新版本的 wasm_bindgen (v0.2.55)。我认为这应该是可能的,对吧?

4

1 回答 1

7

看起来还不可能,这里有一个相关的问题。提到的一些解决方法包括通过 Serde 序列化/反序列化字节或 JSON。但是转换为 JSArray看起来像是 Pauan 添加的更好的解决方法。用你的例子,看看这是否适合你:

use js_sys::Array;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Dummy {}

#[wasm_bindgen]
pub fn test() -> Array {
    let dummies: Vec<Dummy> = vec![];
    dummies.into_iter().map(JsValue::from).collect()
}
于 2019-11-22T14:47:12.167 回答