Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Vec<T> as return type and make it readable in Javascript with wasm_bindgen

I want to compile the following code.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Dummy {}

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

However, the compiler doesn't allow me to do that.

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>`

I'm using the latest version of wasm_bindgen (v0.2.55). I think this should be possible, right?

like image 698
buckle2000 Avatar asked Nov 22 '19 03:11

buckle2000


1 Answers

Doesn't look like it's possible yet, there's a related issue here. Some workarounds mentioned include serializing/deserializing bytes or JSON via Serde. But converting to a JS Array looks like a nicer workaround added by Pauan. With your example, see if this works for you:

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()
}
like image 82
dchang Avatar answered Nov 09 '22 05:11

dchang