Rust implementing From trait and specialization

According to the specialization RFC, I should be able to have multiple impls of the same trait on a struct by specifying one as default.

Currently, I something similar to the code below.

#![feature(specialization)]
struct A(u32);

trait Dummy {}

impl<T> From<T> for A where T: Into<u32> {
    default fn from(item: T) -> Self {
        A(item.into())
    }
}

impl<T> From<T> for A where T: Dummy {
    fn from(item: T) -> Self {
        A(2)
    }
}

Even though one of the implementations is default, the compiler still tells me that the two are conflicting implmentations.

For specialization to be applicable here, there needsto be a "clear hierarchy" between the trait bounds:

  • either all T : Dummy are also T : Into<u32>, and then Into<u32> can have a more specialized impl than Dummy's (thus the latter is the one needing the default qualifier)

    • this can be achieved with, for instance, a super trait

      trait Dummy : Into<u32> {}
      
  • or all T : Into<u32> are also T : Dummy, and then Dummy can have a more specialized impl than Into<u32>'s (thus the latter is the one needing the default qualifier)

    • this can be achieved with, for instance, a generic impl

      impl<T : Into<u32>> Dummy for T {}
      
  • Playground

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.