12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

wasmのRustではVec型をreturnできない

Last updated at Posted at 2019-08-28

詰まったこと

現在個人開発しているサービスで,文字列を処理するスクリプトをwasmで書こうとしていた。

extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn text_parser(text: &str) -> Vec<String>{
    let mut formatted_text = vec![];

    // textをパースしてformatted_textに格納していく
    
    return formatted_text;
}

これをコンパイルしようとしたところ以下のエラーが発生

error[E0277]: the trait bound `std::boxed::Box<[std::string::String]>: wasm_bindgen::convert::IntoWasmAbi` is not satisfied
 --> src/lib.rs:4:1
  |
4 | #[wasm_bindgen]
  | ^^^^^^^^^^^^^^^ the trait `wasm_bindgen::convert::IntoWasmAbi` is not implemented for `std::boxed::Box<[std::string::String]>`
  |
  = help: the following implementations were found:
            <std::boxed::Box<[f32]> as wasm_bindgen::convert::IntoWasmAbi>
            <std::boxed::Box<[f64]> as wasm_bindgen::convert::IntoWasmAbi>
            <std::boxed::Box<[i16]> as wasm_bindgen::convert::IntoWasmAbi>
            <std::boxed::Box<[i32]> as wasm_bindgen::convert::IntoWasmAbi>
          and 9 others
  = note: required because of the requirements on the impl of `wasm_bindgen::convert::IntoWasmAbi` for `std::vec::Vec<std::string::String>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `text_formatter`.

To learn more, run the command again with --verbose.

公式のIssueを見たところ、どうもwasmを使う場合返り値にVec型を指定できないらしい

対策

extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn text_parser(text: &str) -> String{
    let mut formatted_text = vec![];

    // textをパースしてformatted_textに格納していく
    
    return formatted_text.iter().cloned().collect::<String>();
}

今回は単純にStringにまとめてもJS側でどうにかできたのでStringにまとめて返り値にした。
そうは行かない場合、JSON形式にまとめてStringにしてから返り値にするなどの対策がある。

しかしなかなか面倒な処理が必要となるので、できれば早く公式の方で対応してほしいところである。

12
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?