2

I'm having trouble implementing the Into trait for a generic struct in Rust. A simplified version of what I am trying to do is below:

struct Wrapper<T> {
    value: T
}

impl<T> Into<T> for Wrapper<T> {
    fn into(self) -> T {
        self.value
    }
}

When I try to compile, I get the following error:

error: conflicting implementations of trait `std::convert::Into<_>` for type `Wrapper<_>`: [--explain E0119]
 --> <anon>:5:1
  |>
5 |> impl<T> Into<T> for Wrapper<T> {
  |> ^
note: conflicting implementation in crate `core`

I get the impression that the problem is the following implementation in the standard library:

impl<T, U> Into<T> for U where T: From<U>

Since T might implement From<Wrapper<T>>, this might be a conflicting implementation. Is there any way around this problem? For example, is there a way to have an impl<T> block restricting T to types that do not implement From<Wrapper<T>>?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Iceberg
  • 376
  • 1
  • 12

1 Answers1

3

Actually... there isn't a way to restrict this to types T not implementing From<Wrapper<T>>. Rust does not have "negative" clauses.

Normally, the way to implement Into is simply to implement From and get Into for free. However, in your case the implementation would be:

impl<T> From<Wrapper<T>> for T {
    fn from(w: Wrapper<T>) -> T { w.value }
}

and this runs into the orphan rules. You are not allowed to implement From for all T.

There might be a trick, but I cannot see it here.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722