Impl From for "transparent" type

I has Feet type:

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Feet<T>(T);

And I want such code to work:

    let x = Feet::<u16>(1);
    let mut y = Feet::<u32>(2);
    y = Feet::<u32>::from(x);

So I wrote such code:

impl<T, U> From<Feet<T>> for Feet<U>
where
    U: From<T>,
{
    #[inline]
    fn from(value: Feet<T>) -> Self {
        Feet(U::from(value.0))
    }
}

The problem that exists generic T: From<T> , and in case U == T, my new implementation conflicts with core one.

Any way to solve this problem, and make possible Feet::<u32>::from(x) ?

You can't use the From trait like that.

So it is impossible to implement From trait for custom types, and I need implement it as methods of Feet or by introducing new trait MyFrom?

If you want a generic implementation then yes. But you could implement it for every concrete type you want to support. I.e. your Feet wrapper is probably only going to be used with numeric types, so you could implement From<u8, u16, u32, ...> for it manually (probably with the help of a declarative macro). For you to be able to get a generic From implementation for your type, specialization needs to get fixed and stabilized, which is nothing you should hope for anytime soon.

3 Likes

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.