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

Order of operands to equality expression matters when inferring a AsRef implementation #23762

Open
shepmaster opened this Issue Mar 26, 2015 · 2 comments

Comments

Projects
None yet
5 participants
@shepmaster
Copy link
Member

shepmaster commented Mar 26, 2015

This may be related to or the same as #23673, but I wanted to file it anyway as it seems to have a slightly different flavor.

#![feature(convert)]

struct Container {
    i: u8,
    b: bool,
}

impl AsRef<u8> for Container {
    fn as_ref(&self) -> &u8 {
        &self.i
    }
}

// A second implementation to make the `as_ref` ambiguous without further information
impl AsRef<bool> for Container {
    fn as_ref(&self) -> &bool {
        &self.b
    }
}

fn main() {
    let c = Container { i: 42, b: true };

    // Succeeds
    &42u8 == c.as_ref();

    // Fails
    c.as_ref() == &42u8;
}

Fails with

type annotations required: cannot resolve `Container : core::convert::AsRef<_>` [E0283]

However, if you flip the order of the arguments to the equality operator, then the code compiles and the correct type is inferred. It seems as if both forms should work the same.

Originally from this Stack Overflow question

@hawkw

This comment has been minimized.

Copy link

hawkw commented Apr 12, 2015

I've seen what (appears to be) a similar issue when trying to use as_ref() in a pattern guard expression.

@brson

This comment has been minimized.

Copy link
Contributor

brson commented Dec 1, 2016

Still repros.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.