Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

Rust の WebAssembly(wasm) の web-sys を使うときは Cargo.toml で features を指定する必要あり

Rust で WebAssembly しようとやってみたら最初でつまづいたのでメモ。

Cargo.toml

[dependencies]
web-sys = "0.3.57"

main.rs (trunk 使ってみてるので)

pub func main() {
    let window = web_sys::window().unwrap();
}
error[E0425]: cannot find function `window` in crate `web_sys`
 --> src/main.rs:6:27
  |
6 |     let window = web_sys::window().unwrap();
  |                           ^^^^^^ not found in `web_sys`



どうやら web-sys は膨大な内容を取り扱っているのと、最終成果物の WebAssembly のバイナリをできる限り小さくするために、デフォルトで全部機能をオフにしているらしい。
なので、使うものだけを Cargo の features に列挙していく必要がある。

Cargo.toml

[dependencies.web-sys]
version = "0.3.57"
features = [
  'Window'
]



https://rustwasm.github.io/wasm-bindgen/api/web_sys/

↑ここの Structs からそれっぽいやつを見つけて、詳細ページを見に行くと追加すべき features が書いてあるのでそれを Cargo.toml に追加する。

たとえば window.document() とつなげたければ Struct web_sys::Document を見に行って Document を追加すべきだとわかる。

Rust で { と } を表示する

error: invalid format string: expected `'}'`, found `'{'`

{ hoge } という文字列を println! しようとしたら、エラーになった。

let s = "hoge";
println!("{ {} }", s);
error: invalid format string: expected `'}'`, found `'{'`
   --> src\main.rs:316:21
    |
316 |         println!("{ {} }", s);
    |                   - ^ expected `}` in format string
    |                   |
    |                   because of this opening brace
    |
    = note: if you intended to print `{`, you can escape it using `{{`

コンパイラが教えてくれたとおり、{{ と }} を使えば OK。
他の言語だとバックスラッシュとかかなと思ったけど違った。

println!("{{ {} }}", s);
{ hoge }

Rust の to_owned() って何

to_owned()

https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned

  • &の参照に対して使う
  • 参照元の値をクローンする
  • クローンした上で所有権も新規にする(参照元の方の所有権はそのまま)

fn main() {
    {
        let s1: &str = "foo";
        let s2: &str = (&s1).to_owned();
        println!("{}", s1);
        println!("{}", s2);
    }
    {
        let s1: String = "bar".to_string();
        let s2: String = (&s1).to_owned();
        println!("{}", s1);
        println!("{}", s2);
    }
    {
        let v1: Vec<i32> = vec![0, 1, 2, 3, 4, 5];
        let v2: Vec<i32> = (&v1[1..3]).to_owned();
        println!("{:?}", v1);
        println!("{:?}", v2);
    }
}
foo
foo
bar
bar
[0, 1, 2, 3, 4, 5]
[1, 2]