Is the impl From<T> for T too generic?

Recently, I found myself wanting to use Option<T>.into::<Option<U>>() where T: Into<U>, but I realized that this wasn't a part of the standard library. I subsequently wanted to contribute an implementation (which would be as simple as |i| i.map(|j| j.into())), but realized that the compiler does not allow it with E0119. If I understand the problem correctly, it is because the types U and T may be identical, which would lead to the monomorphized implementation trying to override the one in libcore (that is, if there is one and it's not implicit). If my diagnosis is correct, is there a way to communicate U != T to the compiler?

I have a contrived example of this on the playground, should anyone want to tweak it.

1 Like

You want specialization, this is one of the classic use cases. it is available in incomplete state on nightly and in progress

There is currently no good way to implement this

1 Like

I think this would also need the "lattice" rule of specialization:
https://rust-lang.github.io/rfcs/1210-impl-specialization.html#the-lattice-rule

The two impls only partially overlap, so you need a third to resolve the intersection.

impl<T> From<T> for T {...}
impl<T, U: From<T>> From<Option<T>> for Option<U> {...}
impl<T> From<Option<T>> for Option<T> {...} // intersection
3 Likes

Thanks @IndianBoy42 and @cuviper, I’ll keep an eye out for when it’s completed and stabilized.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.