Renato
Renato

Reputation: 13690

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?

Upvotes: 2

Views: 3985

Answers (2)

Renato
Renato

Reputation: 13690

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>());
}

Upvotes: 2

schrieveslaach
schrieveslaach

Reputation: 1819

With the use of js_sys you can create arrays like this:

use js_sys::Array;

#[wasm_bindgen]
pub fn strings() -> Array {
    let arr = Array::new_with_length(10);
    for i in 0..arr.length() {
        let s = JsValue::from_str(&format!("str {}", i));
        arr.set(i, s);
    }
    arr
}

But can you give an example with string literals like ["hello"].to_array()

For the requested example you cannot use any method to convert directly. Therefore, you have to use a helper function:

#[wasm_bindgen]
pub fn strings() -> Array {
    to_array(&["str 1", "str 2"])
}

pub fn to_array(strings: &[&str] ) -> Array {

    let arr = Array::new_with_length(strings.len() as u32);
    for (i, s) in strings.iter().enumerate() {
        arr.set(i as u32, JsValue::from_str(s));
    }
    arr
}

Upvotes: 1

Related Questions