Search code examples
rusttraits

Exclude type from trait bounds


While playing around with Rust and its generics I came along some problem for which I cannot find any documentation.

I have implemented a type Wrapper which wraps another type. At some point I wanted to implement the From trait.

impl<TSrc, TDst> From<Wrapper<TSrc>> for Wrapper<TDst> 
where
   TSrc: From<TDst> 
{
    fn from(other: Wrapper<TSrc>) -> Self {
        todo!()
    }
}

rustc complains with following error

58 | impl<TSrc, TDst> From<Wrapper<TSrc>> for Wrapper<TDst>
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> From<T> for T;

This makes sense if TSrc and TDst are the same. Is it somehow possible to explicitly exclude TSrc from TDst?


Solution

  • No, it is not possible to exclude specific types in a generic implementation.

    There's not really a general workaround beyond "do something else" which would typically look like an inherent conversion method, using a different (custom) trait, or allowing another mechanism for users to access the inner values and do the conversion themselves.

    There may be mechanisms in the future like specialization or negative impls that could allow such an implementation (or similar), but nothing is on the horizon.

    See also: