#Newtype or newtrait?

13 messages · Page 1 of 1 (latest)

frigid nymph
#

I'm using two crates exposing a very similar enum.

It's not possible for me to implement From<T> for any of them because of the orphan rule.

I've read about the ✨newtype pattern✨ as a solution to the orphan rule.

As an alternative to using the newtype pattern, I've experimented with just creating a new trait, LocalFrom<T>.

Do we call this newtrait pattern or what?

What would be the implications of doing this instead of creating a newtype? Or am i just complicating things, and this is exactly the same as the newtype pattern?

jolly night
#

if you’re making a new trait, why not just expose it as a function at that point?

frigid nymph
#

Hmm, I'm not sure i understand your question. Let me elaborate on my use case:

I've got two different Enum types that i want to convert into u8. Since I'm implementing my new LocalFrom<T> for these enums, I can then do this type conversion for both enums using value.local_into::<u8>().

I guess I could implement a two functions as an alternative. One for each enum, but using this trait the local_into() function is more easily "discovered" by future developers trying to do these conversions

jolly night
#

have you considered using an extension trait on the enums?

#

It just seems odd to make a LocalFrom trait if you’re never goïng to be generic over that bound

frigid nymph
#

Hmm, interesting! Have not heard of this before

#

What would separate this solution from using extension traits?

jolly night
#

your solution is more abstract

#

but it seems to be using a level of abstraction that you don’t actually need

#

which is why I’m warning against it

frigid nymph
#

Alright, I see

#

I need to read up on this

#

Thank you! 🙌