Help with this From trait implementation

pub struct Handle<T> {
    data: T,
}

impl<S: From<T>, T> From<Handle<T>> for Handle<S> {
    fn from(value: Handle<T>) -> Self {
        Self {
            data: value.data.into(),
        }
    }
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait `From<Handle<_>>` for type `Handle<_>`
 --> src/lib.rs:5:1
  |
5 | impl<S: From<T>, T> From<Handle<T>> for Handle<S> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: conflicting implementation in crate `core`:
          - impl<T> From<T> for T;

For more information about this error, try `rustc --explain E0119`.
error: could not compile `playground` (lib) due to 1 previous error

Multiple blanket impls are generally not possible. Consider what would happen if S = T. That would clash with the already-existing impl From<T> for T defined by std.

Just write From impls for concrete types, or none at all (use an inherent method instead).

1 Like

You can make it an inherent method:

impl<T> Handle<T> {
    pub fn convert<S>(self) -> Handle<S>
    where
        T: Into<S>,
    {
        Handle {
            data: self.data.into(),
        }
    }
}

You'll get basically the same ergonomics. And the constraints are much simpler.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.