Trait Impl Collision (assert `TypeA != Type B` ?!)

Motivation. I have a type Matrix<T> which represents a matrix with entries of type T. I implement FromStr for Matrix<T> where T : FromStr. What it does is parsing a matrix, by finding delimiters like [,], and then parsing the entries with the from_str() method on T.
Now of course I need some error type for this parsing, something like this:

enum ParsingError<T: FromStr> {
    Other,
    EntryParsingError(T::Err),
}

What's important is the second variant, which stores the "parsing error" from parsing an entry.

Problem. Now of course I want a nice From implementation for my error type, so that I can use the ? operator. In particular I want something like this:

impl<T: FromStr> From<T::Err> for ParsingError<T> {
    fn from(value: T::Err) -> Self {
        Self::EntryParsingError(value)
    }
}

Now, the problem is, this does not compile! It complains that the From implementation conflicts with the blanket implementation impl<T> From<T> for T.

I guess the problem is that T::Err could theoretically be ParsingError. Of course this will never happen. (Except when I would build a matrix of matrices.) So what would be a good solution? It would be great if I could have a "negative type bound" to assert that T::Err should not be ParsingError or something like that.

a simple workaround is instead of put the FromStr::Err projection into the ParsingError type, put it into the implementation:

// no mention of `FromStr::Err` here
enum ParsingError<E> {
    Other,
    EntryParsingError(E),
}
impl<E> From<E> for ParsingError<E> {
    fn from(e: E) -> Self {
        ParsingError::EntryParsingError(e)
    }
}

impl<T: FromStr> FromStr for Matrix<T> {
    // but mention `FromStr::Err` here:
    type Err = ParsingError<T::Err>;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        todo!()
    }
}

1 Like