*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
Description
opened on Jul 1, 2024
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)
Metadata
Assignees
Labels
Area: The borrow checkerArea: Messages for errors, warnings, and lintsArea: documentation for any part of the project, including the compiler, standard library, and toolsArea: trait objects, vtable layoutCategory: This is a bug.Relevant to the compiler team, which will review and decide on the PR/issue.
Activity