Crate dyn_eq

source ·
Expand description

github crates.io license passively-maintained

This crate provides a DynEq trait which permit comparing trait objects. If the two objects are instances of different structs, they will always be not equal. If they are instances of the same struct, the struct’s Eq will be used.

Todos

Here’s a list of things that could be done and could be nice to have, but I’ll implement them only if someone ask:

  • Permit having PartialEq without Eq (implementation on dyn Trait will follow)

Features

This crate has one feature: alloc, which is enabled by default. Disabling this feature removes the dependency on the alloc crate, but you won’t be able to use DynEq for Box<dyn Trait>.

Example

use dyn_eq::DynEq;

trait MyTrait: DynEq {}
dyn_eq::eq_trait_object!(MyTrait);

impl MyTrait for u8 {}
impl MyTrait for u16 {}

let a: &dyn MyTrait = &5u8;
let a_bis: &dyn MyTrait = &5u8;
let b: &dyn MyTrait = &10u8;
let c: &dyn MyTrait = &5u16;
let d: &dyn MyTrait = &10u16;

// Same type, same value
assert!(a == a_bis);
// Same type, different value
assert!(a != b);
// Different type, different value
assert!(a != d);
// Different type, same value
// Even if the value is the same, the fact that it's a diffrent type means it's not equal
assert!(a != c);

// Now data structures containing Box<dyn MyTrait> can derive Eq (only when `alloc`
// feature is enabled).
#[derive(PartialEq, Eq)]
struct Container {
    field: Box<dyn MyTrait>
}

Macros

Traits

  • This trait is implemented by any type that implements Eq.