2 ms·
The term "Newtype" more specifically describes a wrapper around a single type. It's like an alias. It's incorrect to describe an enum with two variants as a 'n
by rgoulter 3y ago
The term "Newtype" more specifically describes a wrapper around a single type. It's like an alias.
It's incorrect to describe an enum with two variants as a 'newtype'.
I think the example was misunderstood from https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html https://rust-unofficial.github.io/patterns/patterns/behaviou... (which uses Password, but doesn't use an enum with two variants).
The use of enums in the example is fine; but it's not a "newtype".
- junon 3y agoMore specifically the newtype pattern is mostly so that you can implement foreign traits on foreign types. You can't normally do this since there's a high risk of duplicate implementations, so by enforcing only local types/foreign traits or foreign types/local traits (and of course local/local types and traits), this duplication doesn't occur - there's only ever one implementation of a trait per type, and the ownership of those implementations is very clear and we'll defined. The newtype pattern simply makes a "local" type that wraps a foreign type, allowing you to implement the foreign trait on the new local type, and forwarding calls of the trait methods to the inner type - all while maintaining the single trait impl and ownership constraints rust imposes. Further, given all of the compiler optimizations that happen, newtypes are effectively free. For those who haven't seen it, this is what newtype looks like: use some::ForeignType; struct LocalType(ForeignType); As the parent comment states, it has nothing to do with enums.
- ReleaseCandidat 3y ago> More specifically the newtype pattern is mostly so that you can implement foreign traits on foreign types. For some definition of "mostly". I use most of my newtypes neither in Rust nor in Haskell to implement traits, but most of the time to declare - newtypes ;) that wrap other (primitive) types.
- stmblast 3y agoHey, author here! Thanks for the feedback. I agree that this could have been worded better - I'll make an adjustment to change this.