Created
May 6, 2018 14:28
-
-
Save jlgerber/bb39ef312c876f0b75ae702eeea55799 to your computer and use it in GitHub Desktop.
getting around inability to use PartialEq and PartialOrd with trait objects. from https://users.rust-lang.org/t/testing-equality-with-a-trait-object/5034/6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::any::Any; | |
trait Schema { | |
fn eq(&self, other: &Schema) -> bool; | |
fn as_any(&self) -> &Any; | |
} | |
impl<'a, 'b> PartialEq<Schema+'b> for Schema+'a { | |
fn eq(&self, other: &(Schema+'b)) -> bool { | |
Schema::eq(self, other) | |
} | |
} | |
#[derive(PartialEq)] | |
struct Foo(i32); | |
impl Schema for Foo { | |
fn eq(&self, other: &Schema) -> bool { | |
other.as_any().downcast_ref::<Self>().map_or(false, |x| x == self) | |
} | |
fn as_any(&self) -> &Any { self } | |
} | |
#[derive(PartialEq)] | |
struct Bar; | |
impl Schema for Bar { | |
fn eq(&self, other: &Schema) -> bool { | |
other.as_any().downcast_ref::<Self>().map_or(false, |x| x == self) | |
} | |
fn as_any(&self) -> &Any { self } | |
} | |
fn main() { | |
let foo1: &Schema = &Foo(1); | |
let foo2: &Schema = &Foo(2); | |
let bar: &Schema = &Bar; | |
if foo1 == foo1 && foo1 != foo2 && foo1 != bar { | |
println!("Hello, world!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The author is stevenblenkinsop
the thread is here:
https://users.rust-lang.org/t/testing-equality-with-a-trait-object/5034/6