Open
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)
Metadata
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.
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
PartialEq
#124157eggyal commentedon Jul 2, 2024
Interestingly it works if the arguments to
f
areBox<dyn Animal>
or&dyn Animal
rather than&Box<dyn Animal>
.finnbear commentedon Aug 11, 2024
Same issue occurs if the container, in this case
RcPtrEq
, implementsPartialEq
independently of thedyn
trait object:Playground link
Strangely, removing
CoercedUnized
makes it compile.Artikae commentedon Sep 12, 2024
This also breaks the PartialEq derive macro when used on structs.
Playground link
SaltyKitkat commentedon Oct 31, 2024
I met this problem. It's quite annoying for me since I cannot use
PartialEq
derive macro.So is there any progress on this recently?
QuineDot commentedon Dec 31, 2024
An earlier duplicate:
#31740