Wasm-bindgen: How do you use a Rust struct with a `String` field?

Created on 19 Sep 2019  路  7Comments  路  Source: rustwasm/wasm-bindgen

Summary

How do you use a Rust struct with a String field using wasm-bindgen?

The String type seems to be supported for function parameters and return values. https://rustwasm.github.io/docs/wasm-bindgen/reference/types/string.html

Additional Details

#[wasm_bindgen]
pub struct Data {
    id: String,
}
question

Most helpful comment

Now that being said, it'd be a neat feature to do something like #[wasm_bindgen(getter_setter_with_clone)] or something like that so the boilerplate could be drastically reduced

All 7 comments

Thanks for the report! For this you'll want to use getters and setters, and that shoul dod the trick!

That worked! Thank you.

Hi @garrettmaring can you share some details how exactly you solved it with getters and setters? thanks

Sure!

// doesn't work...
#[wasm_bindgen]
struct Data {
    pub id: String,
}

You'll get the error error[E0277]: the trait bound std::string::String: std::marker::Copy is not satisfied.

Since, the String type in Rust isn't implicitly copyable. I had to read up on the difference between Copy and Clone to understand that I couldn't just implement Copy but rather needed to use .clone() to explicitly copy it.

Thankfully, _wasm-bindgen_ gives us a simple way to do it.

#[wasm_bindgen]
struct Data {
    id: String, // ensure that the field is private
}

#[wasm_bindgen]
impl Data {
    #[wasm_bindgen(getter)]
    pub fn id(&self) -> String {
        self.id.clone()
    }

    #[wasm_bindgen(setter)]
    pub fn set_id(&mut self, id: String) {
        self.id = id;
    }
}

There are some interesting things that you can do with getters and setters that are documented here.

@alexcrichton would it be feasible for _wasm-bindgen_ to generate this code if a struct implements Clone?

It's plausible, yeah! It's something though we've avoided doing historically because a Clone implementation can often be accidentally quite expensive, so we tend to prefer to request that users do so manually to ensure they know the cost they're opt-ing into

Now that being said, it'd be a neat feature to do something like #[wasm_bindgen(getter_setter_with_clone)] or something like that so the boilerplate could be drastically reduced

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pauldorehill picture pauldorehill  路  3Comments

poccariswet picture poccariswet  路  3Comments

fitzgen picture fitzgen  路  4Comments

fitzgen picture fitzgen  路  3Comments

MarcAntoine-Arnaud picture MarcAntoine-Arnaud  路  3Comments