Search code examples
rustwasm-bindgenrust-wasm

How to create a JS array of Strings from Rust using web_sys?


I am trying to use a Web API that contains a method which accepts an array of strings from Rust.

I am using web_sys to "talk" to the JS API, but I can't find a way to pass in an array of static Strings into it.

In Rust, unfortunately, the type of the parameter is mistakenly declared as arg: &JsValue, so I can pass just about anything into it and it still compiles, but crashes in the browser.

How can I create an array of strings in Rust that can be used as a &JsValue?


Solution

  • This converts &[&str] to JsValue:

    fn js_array(values: &[&str]) -> JsValue {
        return JsValue::from(values.into_iter()
            .map(|x| JsValue::from_str(x))
            .collect::<Array>());
    }