rust-orphan-rules icon indicating copy to clipboard operation
rust-orphan-rules copied to clipboard

Generic From impl for newtypes

Open dhardy opened this issue 6 years ago • 2 comments

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.

dhardy avatar Oct 08 '19 10:10 dhardy

Would specialization help with this case?

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

Ixrec avatar Oct 08 '19 10:10 Ixrec

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 }
}

dhardy avatar Oct 08 '19 14:10 dhardy