I'm trying to implement PartialEq
in Rust for a trait that has subtypes, so that I can add them as boxed pointers to a container and later compare them.
Here's my scaled-down implementation:
use std::any::Any;
trait Foo: Any {}
struct Bar {}
impl Foo for Bar {}
struct Baz {}
impl Foo for Baz {}
impl PartialEq for Foo {
fn eq(&self, other: &Foo) -> bool {
let me = self as &Any;
let you = other as &Any;
if me.is::<Bar>() && you.is::<Bar>() {
true
} else if me.is::<Baz>() && you.is::<Baz>() {
true
} else {
false
}
}
}
fn main() {
let bar: Bar = Bar {};
let baz: Baz = Baz {};
let foo1: &Foo = &bar;
let foo2: &Foo = &baz;
println!("{:?}", foo1 == foo2);
}
Code example in Rust Playground.
When I build this, I get:
rustc 1.17.0-nightly (0648517fa 2017-02-03)
error: non-scalar cast: `&Foo + 'static` as `&std::any::Any + 'static`
--> <anon>:15:18
|
15 | let me = self as &Any;
| ^^^^^^^^^^^^
error: non-scalar cast: `&Foo + 'static` as `&std::any::Any + 'static`
--> <anon>:16:19
|
16 | let you = other as &Any;
| ^^^^^^^^^^^^^
error: aborting due to 2 previous errors
which is confusing. Any ideas what I'm doing wrong here?
Edit: I don't believe this is a duplicate of Why doesn't Rust support trait object upcasting?, because what I'm trying to do is downcast using Any
, not upcast.
Further Edit: Yes, this is a duplicate - sorry, I was thinking about what I was trying to do (downcast to the Bar
and Baz
types) rather than how I was doing that (upcasting to Any
). However, that being said, I guess I still don't understand why the Any example, where they do this: let value_any = value as &Any;
works, where mine doesn't. That being said, Joshua Entrekin did give a great answer.
Final Edit An, never mind, it's because I'm upcasting a trait rather than a type - Doh!. Thanks, everyone!