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

Types should implement AsRef for themself #1582

Closed
Pauan opened this issue Jun 10, 2019 · 0 comments · Fixed by #1583
Closed

Types should implement AsRef for themself #1582

Pauan opened this issue Jun 10, 2019 · 0 comments · Fixed by #1583

Comments

@Pauan
Copy link
Contributor

Pauan commented Jun 10, 2019

Motivation

I'm working on porting dominator to use wasm-bindgen, and I ran into this big issue.

Dominator contains a struct DomBuilder<A> which allows it to work on any type. Then I implement methods only for certain types:

impl<A> DomBuilder<A> where A: AsRef<Node> {
    pub fn children(...) { ... }
    ...
}

impl<A> DomBuilder<A> where A: AsRef<Element> {
    pub fn class(...) { ... }
    ...
}

impl<A> DomBuilder<A> where A: AsRef<HtmlElement> {
    pub fn style(...) { ... }
    ...
}

The idea is that you can use DomBuilder on any type, but at compile-time it will statically restrict which methods you can use depending on the type.

So you can't use HtmlElement methods on a Node, for example. But you can use Node methods on a Node, Element, or HtmlElement.

This works great in stdweb, but it doesn't work in wasm-bindgen, because wasm-bindgen implements these...

impl AsRef<JsValue> for HtmlElement
impl AsRef<Object> for HtmlElement
impl AsRef<EventTarget> for HtmlElement
impl AsRef<Node> for HtmlElement
impl AsRef<Element> for HtmlElement

...but it does not implement impl AsRef<HtmlElement> for HtmlElement

That's a big problem, since it means that you cannot write code which is generic over the type.

Proposed Solution

Implement impl AsRef<Foo> for Foo for all types created by the #[wasm_bindgen] macro.

Alternatives

  • Create a new trait that is similar to AsRef (seems redundant).

  • Don't do this (makes writing generic code impossible).

Additional Context

There is precedence for this, since the stdlib defines these:

impl AsRef<CStr> for CStr
impl AsRef<OsStr> for OsStr
impl AsRef<Path> for Path
impl<T> AsRef<Vec<T>> for Vec<T>

And wasm-bindgen itself defines impl AsRef<JsValue> for JsValue

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

Successfully merging a pull request may close this issue.

1 participant