Unable to impl multiple generic From traits

#1

I have an enum that takes two generic types and I wanted to implement two different from implementations. However, it seems that there isn’t generic type bounds for not equals. Is there anyway to get around this?

Code example:

pub enum AstLink<T, U> {
    PreLink(T),
    PostLink(U)
}

impl <T, U> From<T> for AstLink<T, U> {
    fn from(item: T) -> Self {
        AstLink::PreLink(item)
    }
}

impl <T, U> From<U> for AstLink<T, U> {
    fn from(item: U) -> Self {
        AstLink::PostLink(item)
    }
}
#2

I first thought maybe trait specialization would handle it but It’s actually hard for the compiler to decide on the overlap in this very generic case, see. So it’d encourage to be more explicit like this. This is related to trait coherence

Finally, I thought I can help compiler but didn’t work :frowning:

1 Like
#3

If you want a creative (And unstable!) solution, inspired from my solution to The `Squeeze` challenge, then look at this. Note that this disallows you from using the () unit in the link. You could do something similar with the ! never type to eliminate that like this.