Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returning Vec<String> from an async function fails to compile #3793

Closed
FredrikNoren opened this issue Jan 18, 2024 · 4 comments
Closed

Returning Vec<String> from an async function fails to compile #3793

FredrikNoren opened this issue Jan 18, 2024 · 4 comments
Labels

Comments

@FredrikNoren
Copy link

Describe the Bug

This code:

#[wasm_bindgen]
pub async fn get_strings() -> Vec<String> {
    vec!["hello".to_string(), "world".to_string()]
}

Expected Behavior

Should compile,

Actual Behavior

But gives the following compilation error:

the trait bound `wasm_bindgen::JsValue: From<Vec<std::string::String>>` is not satisfied
the following other types implement trait `From<T>`:
  <wasm_bindgen::JsValue as From<bool>>
  <wasm_bindgen::JsValue as From<isize>>
  <wasm_bindgen::JsValue as From<i8>>
  <wasm_bindgen::JsValue as From<i16>>
  <wasm_bindgen::JsValue as From<i32>>
  <wasm_bindgen::JsValue as From<i64>>
  <wasm_bindgen::JsValue as From<i128>>
  <wasm_bindgen::JsValue as From<usize>>
and 100 others
required for `Vec<std::string::String>` to implement `Into<wasm_bindgen::JsValue>`
required for `Vec<std::string::String>` to implement `IntoJsResult`

Additional Context

wasm-bindgen = "0.2"

@matthiasgeihs
Copy link

same here

@samankittani
Copy link

samankittani commented Jun 25, 2024

There is a way around this, but it is ugly. If you define a newtype for Vec:

pub struct VecString(Vec<String>);

Then you can impl From for VecString.

impl From<VecString> for JsValue {
    fn from(value: VecString) -> Self {
        serde_wasm_bindgen::to_value(&value).unwrap()
    }
}

You will need serde_wasm_bindgen.
I can't impl it for Vec directly because of Rust's orphan rule. You'll need the serde_wasm_bindgen crate. I am trying to find a more elegant solution

@samankittani
Copy link

samankittani commented Jun 25, 2024

Here is a better solution #3630
This will likely be fixed in the next release. In the meantime, I am adding this to my cargo.toml file:

[patch.crates-io]
wasm-bindgen = { git = "https://github.com/rustwasm/wasm-bindgen", rev = "88efe46" }

This will use the wasm-bindgen version that includes the commit that supports Vec for async functions

@daxpedda
Copy link
Collaborator

Considering #3630 has already been merged, I'm gonna go ahead and close this.
Let me know of this turns out to still not be fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants