Skip to content

== operator does not support subtyping #27949

Closed
@daboross

Description

@daboross

Here's an example showing this behavior:

struct Input<'a> {
    foo: &'a u32
}

impl <'a> std::cmp::PartialEq<Input<'a>> for Input<'a> {
    fn eq(&self, other: &Input<'a>) -> bool {
        self.foo == other.foo
    }

    fn ne(&self, other: &Input<'a>) -> bool {
        self.foo != other.foo
    }
}


// same error if no lifetime parameters are used, but I'm using explicit lifetime parameters to try to show the actual error
fn bar<'a, 'b>(x: Input<'a>, y: Input<'b>) -> bool {
    x == y
}

(https://play.rust-lang.org/?gist=c7b5d06f19fd345eef91)

Errors with:

<anon>:17:5: 17:11 error: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
<anon>:17     x == y
              ^~~~~~
<anon>:16:1: 18:2 help: consider using an explicit lifetime parameter as shown: fn bar<'a>(x: Input<'a>, y: Input<'a>) -> bool
<anon>:16 fn bar(x: Input, y: Input) -> bool {
<anon>:17     x == y
<anon>:18 }
error: aborting due to previous error

Using impl <'a, 'b> std::cmp::PartialEq<Input<'b>> for Input<'a> works, but it is confusing why the below allows lifetime elision while the above doesn't. I would think it would make sense for the rust compiler to merge the minimum of two lifetimes ('a and 'b) automatically when using == if PartialEq is only implemented for one shared lifetime.

impl <'a, 'b> std::cmp::PartialEq<Input<'b>> for Input<'a> {
    fn eq(&self, other: &Input<'b>) -> bool {
        self.foo == other.foo
    }

    fn ne(&self, other: &Input<'b>) -> bool {
        self.foo != other.foo
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions