Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust conflicting implementations for traits

I’m fairly new to Rust, and as a project to make my hands more used to it, I decided to implement a library about category theory and functional programming in general. Long story short, there is a trait called Monad:

pub trait Monad {
// Associated types and functions here
}

And in rust, Options are Monads, so I went like this:

impl<X> Monad for Option<X> {
// Implementation here
}

Everything’s working properly so far. I decided to add a special Monad called Identity Monad, which is a famous and handy one:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type Identity<A> = A;

impl<X> Monad for Identity<X> {
// Implementation here
}

And right there, I get this error: conflicting implementations for Option<_>. Now I have read this SO post, and it makes sense for that use case, but about mine, as far as I can think through, since Identity is a type (not a trait) it may never be the "Option". Can anyone let me know about why’s that happening and what I can do for it?

>Solution :

They conflict because Identity<Option<X>> is the same type as Option<X>.

type does not define a new type, it defines an alias for an existing type; Identity<X> is just another name for X.

You might be interested in the newtype pattern where you create a single-struct field to define a new semantic type wrapping another:

struct Identity<X>(X);

Now Identity<X> is a different type from X, and the implementations would no longer conflict.

If you decorate Identity with #[repr(transparent)] then it’s even possible to safely transmute &X to &Identity<X>, which might be useful depending on the members of Monad.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading