Inheriting / Nesting Traits on other Traits

Viewed 164

In Rust, is it possible to generalize a trait to always implement another trait, or to have a struct "inherit" its traits' implementations of other traits?

For instance, in the following code, I don't want to have to implement equality between every possible type of Length. If I implement it on the trait, how do I use it on the structs that implement that trait?

// `Length` Trait, which includes a standardized unit
trait Length {
  fn _standardized(&self) -> f64;
}
impl std::cmp::PartialEq for dyn Length {
  fn eq(&self, other: &Self) -> bool {
    self._standardized() == other._standardized()
  }
}

// `Centimeters`
struct Centimeters(f64);
impl Length for Centimeters {
  fn _standardized(&self) -> f64 {
    let &Centimeters(cm) = self;
    cm
  }
}

// `Inches`
struct Inches(i32);
impl Length for Inches {
  fn _standardized(&self) -> f64 {
    let &Inches(inches) = self;
    inches as f64 * 2.54
  }
}

fn main() {
  let foot = Inches(12);
  let meter = Centimeters(100.0);

  let cmp = if foot == meter { "equal" } else { "not equal" };
  println!("One foot is {} to one meter.", cmp);
}

Currently, that throws an error:

binary operation `==` cannot be applied to type `partial_ord::Centimeters`

note: an implementation of `std::cmp::PartialEq` might be missing for `partial_ord::Centimeters`
rustc(E0369)

Based on this question, I also tried:

impl<T> std::cmp::PartialEq for T where T: Length {

which gives conflicting implementations of trait `std::cmp::PartialEq<&_>` for type `&_`:

Is there a way to do what I'm trying to do? If so, what is it? (And, if you're looking for extra kudos, what gap in my Rust paradigm does this example highlight?)

0 Answers
Related