LoginSignup
0
0

[Rust->wasm]jsonをwasmで読み込めないので、jsonをコンパイル対象に予め含ませる

Last updated at Posted at 2024-01-10

rustでwasm出力しようとした際に、ブラウザ上でJsonが読み込めず、wasmが表示されないエラーにあたりました。
エラーはブラウザ上で出力されていましたが、原因となるのは以下のコードでした。

        let input_fn = fs::read_to_string("patterns.json").expect("JSON Read Failed.");
        let deserialized: Vec<Hoge> = serde_json::from_str(&input_fn).unwrap();

上記コードのfsだと、ブラウザを走らせた際にwasm側でjsonの読み込みをしようとするのですが、
それに対応する処理が現時点(2024/1/10)ではない模様。
そこでファイルコンパイル対象としてjsonファイルを含ませるように以下の処理に変更すればいいようです。

        let input_fn =include_str!("./patterns.json");
        let deserialized: Vec<Hoge> = serde_json::from_str(&input_fn).unwrap();

include_str!を使うようにした結果、wasmが表示されるようになりました。

include_str!マクロの詳細は以下。

The provided path is interpreted in a platform-specific way at compile time.

参考: https://stackoverflow.com/questions/77767456/read-json-file-in-rust-and-compile-to-wasm

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