Skip to content

Enforce informal properties of traits such as PartialEq #46946

Open

Description

The trait PartialEq represents a partial equivalence — that is, a relation that is symmetric and transitive. However, Rust doesn't currently enforce these properties in any way. This means we get issues like this:

struct A;
struct B;

impl PartialEq<B> for A {
    fn eq(&self, _other: &B) -> bool {
        true
    }
}

fn main() {
    let a = A {};
    let b = B {};
    a == b; // Works
    b == a; // Error (B does not implement PartialEq<A>)
}

This is confusing, but it's usually not so much of an issue in user code, because it's easy to flip the operands. However, when attempting to write generic functions over these traits, you run into problems (for example in #46934).

At the very least there should be a lint warning/error for this. It'd be nice to have a generic solution for properties of traits, though that could come later. It'd be even nicer if the symmetric case for PartialEq, for instance, could be automatically implemented by Rust, though this could require quite a bit more machinery.

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

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: Lints (warnings about flaws in source code) such as unused_mut.A-traitsArea: Trait systemC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language 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