Conversions, TryFrom / TryInto

Let's say I have:

trait Reader {}
struct Message {}

I would like to create a generic implementation for a fallible conversion from any Reader to Message. TryFrom / TryInto seem to be exactly what I would be looking for (I would like to save myself creating my own version of TryFrom / TryInto):

use std::convert::TryFrom;

impl<R> TryFrom<R> for Message
where
    R: Reader,
{
    type Error = ();

    fn try_from(r: R) -> Result<Self, Self::Error> {
        unimplemented!()
    }
}

However (un)surprisingly it results in:

   = note: conflicting implementation in crate `core`:
       - impl<T, U> std::convert::TryFrom<U> for T
         where U: std::convert::Into<T>;

As I understand, what prevents compiler from being happy here is a potential implementation of Into in a third party crate and then not being able to decide which one to choose? However, both, trait and struct are local to my crate so it should not be a problem. What puzzles me more is that following compiles just fine and for me it's pretty much the same thing:

impl<R> From<R> for Message
where
    R: Reader,
{
    fn from(r: R) -> Self {
        unimplemented!()
    }
}

I'm scratching my head for some time trying to find a way around it but having rank Beginner in Rust seems not to be enough...is there any way to make it work?

Basically I could create my own type that implements both Reader and Into<Message> and that would conflict. The compiler doesn't care that your types are not public.

That's what I thought and it kinda makes sense. However, I can't figure out why implementing From does not result in exactly same error and compiles just fine.

It's because implementing Into<Message> directly does not give a From impl. This is why the docs recommend implementing From as opposed to Into.

So in order to conflict when using From, you would have to conflict with the blanket impl that makes T impl From<T>, but this would only happen for T = Message, which the compiler thinks is okay as Message has no Reader impl.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.