Is it possible to specify that the two types of parameters are different types?

I have a simple wrapper structure with a method map

. I also have a hierarchy of error enums where I have implemented From

to be able to convert Error1

to Error2

, allowing the macro to try!

automatically convert for me:

struct Span<T>(T);

impl<T> Span<T> {
    fn map<F, U>(self, f: F) -> Span<U>
        where F: FnOnce(F) -> U
    {
        Span(f(self.0))
    }
}

enum Error1 { One }
enum Error2 { Two }

impl From<Error1> for Error2 {
    fn from(v: Error1) -> Error2 { Error2::Two }
}

      

I would like to add an implementation From

so that I can automatically convert the internals of the struct Span

:

impl<T,U> From<Span<T>> for Span<U>
    where U: From<T>
{
    fn from(v: Span<T>) -> Span<U> {
        v.map(|v| v.into())
    }
}

      

Unfortunately this fails :

error[E0119]: conflicting implementations of trait `std::convert::From<Span<_>>` for type `Span<_>`:
  --> src/main.rs:18:1
   |
18 |   impl<T,U> From<Span<T>> for Span<U>
   |  _^ starting here...
19 | |     where U: From<T>
20 | | {
21 | |     fn from(v: Span<T>) -> Span<U> {
22 | |         v.map(|v| v.into())
23 | |     }
24 | | }
   | |_^ ...ending here
   |
   = note: conflicting implementation in crate `core`

      

The error message does not indicate a specific implementationFrom

, but I think this is one:

impl<T> From<T> for T

      

And that my implementation may conflict if my T

and U

are one and the same specific type. Is there a way to implement your trait for everyone T

and U

where T

! = U

?

+3


source to share


1 answer


Unfortunately, this is not yet possible, and the best approach to this problem has not yet been resolved. One suggestion that pertains a little to this situation is the idea of negative evaluations (in particular equality) , but I find it too difficult. See the final issue on this for more details , where team members look at different ideas, including specialization.



+4


source







All Articles