Implement From for Generic Type


I’m currently writing a network protocol dissector in rust. All message types are implemented as variants of an enum.

I’ve got another struct holding a Message. This Message may be a concrete Message (of type MessageAData) or be of type Message.

What I want now is to be able to convert this struct which holds MessageAData information to a struct that holds Message information. Hence I implement From<MessageAData> for Message. This works as expected, but is much manual work: I have to implement this for every variant on it’s own.
Alternatively I tried to implement a generic variant:

impl<T, V> From<Holder<T>> for Holder<V>
    T: Into<V>,
    fn from(val: Holder<MessageAData>) -> Holder<Message> {
        Holder {
            obj: val.obj.into(),

But the compiler complains that the core’s implementation of impl<T> std::convert::From<T> for T conflicts my implenentation.

Could you please either help me implementing the From trait in a more generic way, or explain why it is not possible (i.e. conflicting)?

Thank you!

Here is a complete playground link to the problem.

Apologies for being concise, I’m on a tablet.

Your From declaration is generic over T, V, but your actual implementation uses concrete types. Change MessageAData to T and Message to V.

The case where T == V is what it is complaining about. This is the default for generic From.

If you don’t need to use From/Into traits you could write your own similar trait or just use a generic function in Holder.

1 Like

That makes sense. Thank you. I think I will define another trait.