Skip to content

*x == *y for trait objects produce move error, so it is not equivalent to PartialEq::eq(&*x, &*y) even though the reference says it is #127215

Open
@estebank

Description

The following code produces a move error:

trait Animal {
    fn noise(&self) -> String;
}

impl PartialEq for dyn Animal {
    fn eq(&self, other: &Self) -> bool {
        self.noise() == other.noise()
    }
}

fn f(a1: &Box<dyn Animal>, a2: &Box<dyn Animal>) {
    println!("{}", *a1 == *a2); // doesn't work
}
error[E0507]: cannot move out of `*a2` which is behind a shared reference
  --> src/lib.rs:12:27
   |
12 |     println!("{}", *a1 == *a2); // doesn't work
   |                           ^^^ move occurs because `*a2` has type `Box<dyn Animal>`, which does not implement the `Copy` trait

But according to the reference, it should be equivalent to the following, which does work:

fn f(a1: &Box<dyn Animal>, a2: &Box<dyn Animal>) {
    println!("{}", PartialEq::eq(&*a1, &*a2)); // works
}

It seems to be specific to trait objects; e.g. replacing Box<dyn Animal> with Box<[String]> will make both versions of f compile.

Originally reported in #123056 (comment)

Activity

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-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-docsArea: documentation for any part of the project, including the compiler, standard library, and toolsA-trait-objectsArea: trait objects, vtable layoutC-bugCategory: This is a bug.T-compilerRelevant to the compiler 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