Ixrec / rust-orphan-rules

An unofficial, experimental place for documenting and gathering feedback on the design problems around Rust's orphan rules
Apache License 2.0
194 stars 3 forks source link

Generic From impl for newtypes #20

Open dhardy opened 4 years ago

dhardy commented 4 years ago

Creating a new issue because this is, in my opinion, probably the most commonly encountered and annoying to work around issue caused by no-orphan rules:

struct NewType<T>(T);

impl<A, B: From<A>> From<NewType<A>> for NewType<B> {
    fn from(a: NewType<A>) -> NewType<B> {
        NewType(a.0.into())
    }
}

Namely, the special case where A == B overlaps with the generic impl<T> From<T> for T.

It's also an instance where it's usually trivial to prove that the overlapping implementations are equivalent, though I realise this is probably not a productive path toward a solution.

Ixrec commented 4 years ago

Would specialization help with this case?

(I don't understand specialization enough to figure that out myself)

dhardy commented 4 years ago

I presume it would, so long as the most generic impl uses the default keyword (assuming specialization will work roughly as in the RFC).

impl<T> From<T> for T {
    default fn from(t: T) -> T { t }
}