概要
Rustでwasmを実装する際に、返り値としてStringを含むstructを返すような場合の対応メモです。
例えば以下のようなstructを実装した場合、std::marker::Copy` is not implemented for `String
というエラーでコンパイルがエラーになります。なお、今回使用しているwasm-bindgenのバージョンは0.2
です。
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct ResultResponse {
pub success_flag: bool,
pub text: String,
}
対応
How declare pub struct with pub fields with wasm_bindgen attributeのissueの記事に、対応方法がいくつか紹介されています。個人的には、#[wasm_bindgen(getter_with_clone)]
をstructに設定する対応が良いかなと思いました。
一応、wasm-bindgenのドキュメントExported struct Whatever Rust Types
にも、#[wasm_bindgen(getter_with_clone)]
の使用について紹介されています。
実装サンプル
以下の通り、structに対して#[wasm_bindgen(getter_with_clone)]
を設定します。
use wasm_bindgen::prelude::*;
#[wasm_bindgen(getter_with_clone)]
pub struct ResultResponse {
pub success_flag: bool,
pub text: String,
}