rustwasm / wasm-bindgen

Facilitating high-level interactions between Wasm modules and JavaScript
https://rustwasm.github.io/docs/wasm-bindgen/
Apache License 2.0
7.75k stars 1.07k forks source link

Non-identifier getters and setters #2227

Open themaxdavitt opened 4 years ago

themaxdavitt commented 4 years ago

Summary

I'm pretty new to the rust-wasm ecosystem but it doesn't seem obvious how to have fields that aren't normal rust identifiers.

Additional Details

I'm trying to export a rust type that's roughly equivalent to this typescript type:

interface TypeContainer {
    '@type': string;
}

I initially was going to create it like this:

#[wasm_bindgen]
pub struct TypeContainer {
    r#type: String,
}

#[wasm_bindgen]
impl TypeContainer {
    #[wasm_bindgen(getter = "@type")]
    pub fn r#type(&self) -> String {
        self.r#type.clone()
    }

    /* ... setter + more ... */
}

But this approach doesn't work for two different reasons:

Obviously I can change the function name to something other than r#type to solve the second issue, but what should I do about wanting a @type field?

alexcrichton commented 4 years ago

Oh interesting, thanks for the report! This is probably an issue where we shouldn't be using the input getter identifier for a Rust identifier. We should probably be using something internal to wasm-bindgen itself. Should be a relatively simple change to the macro code generation to fix this!

themaxdavitt commented 3 years ago

Hey, I know I'm bumping an old issue, but I was curious about this again and just confirmed that this still happens. I still get a complaint about needing an identifier for the getter, and here's the full backtrace and isolated code for that panic from the function name.