Impl Into<B> trait for all types which impl Into<A>

Viewed 627

I wanted to implement a conversion trait that would cover all types supporting already existing conversion. I thought that this could be done in following way:

impl<T> Into<B> for T
where
    T: Into<A>,
{
  fn into(self) -> B {
    let a: A = self.into();
    B::CaseA(a)
  }
}

However compiler throws a following error:

error[E0119]: conflicting implementations of trait `std::convert::Into<block::ItemContent>`
   --> yrs\src\block.rs:945:1
    |
945 | / impl<T> Into<B> for T
946 | | where
947 | |     T: Into<A>,
948 | | {
...   |
952 | |     }
953 | | }
    | |_^
    |
    = note: conflicting implementation in crate `core`:
            - impl<T, U> Into<U> for T
              where U: From<T>;

error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`B`)
   --> yrs\src\block.rs:945:6
    |
945 | impl<T> Into<B> for T
    |      ^ type parameter `T` must be covered by another type when it appears before the first local type (`B`)
    |
    = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type
    = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last

Is it possible to achieve this? I'm looking for a way to automatically extend conversion for a new type for all instances, that support conversion to another existing type.

1 Answers

What you are trying to do can be achieved (as the error says) by covering T with a local type. The reason you cannot do it without that is because otherwise someone else could also do the same and the Rust won't be able to tell which impl to use. So you need a local wrapper type to keep the separation.

The complete reasoning behind this is referenced in the error explanation:

https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md

And https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html

hope this helps ;)

A

Related