Skip to content

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

Open
@shepmaster

Description

@shepmaster

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceA-type-systemArea: Type systemC-bugCategory: This is a bug.I-needs-decisionIssue: In need of a decision.P-lowLow priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions