Skip to content

Overload function names for use in JS #4107

Closed as not planned
Closed as not planned
@devrosch

Description

@devrosch

Summary

The documentation explains very well how to use polymorphic, i.e., overloaded, JavaScript functions in Rust with js_name.

Is a way to do it the other way around too and make multiple Rust functions available to JS under the same name but with different arguments?

Additional Details

Here is minimalistic example that fails to compile.

use js_sys::Uint8Array;
use wasm_bindgen::prelude::wasm_bindgen;
use web_sys::Blob;

#[wasm_bindgen(js_name = Scanner)]
pub struct JsScanner {}

#[wasm_bindgen(js_class = Scanner)]
impl JsScanner {
    #[wasm_bindgen(constructor)]
    pub fn new() -> JsScanner {
        JsScanner {}
    }

    #[wasm_bindgen(js_name = isRecognized)]
    pub fn js_is_recognized_blob(input: &Blob) -> bool {
        todo!()
    }

    #[wasm_bindgen(js_name = isRecognized)]
    pub fn js_is_recognized_uint8array(input: &Uint8Array) -> bool {
        todo!()
    }
}

The error is:

error: symbol `scanner_isRecognized` is already defined
 --> src/lib.rs:8:1
  |
8 | #[wasm_bindgen(js_class = Scanner)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this error originates in the attribute macro `wasm_bindgen::prelude::__wasm_bindgen_class_marker` (in Nightly builds, run with -Z macro-backtrace for more info)

If any one of the the #[wasm_bindgen(js_name = isRecognized)] names are changed the error does not appear. For symmetry with using polymorphic JS functions, it would be very nice to have this work. This question is somewhat related to #1139 but the case here is a bit simpler, I believe.

Is there a way to make this work? Alternatively, is there any workaround?

Thank you for any input on this!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions