2 ms·
This isn’t an issue with the “newtype” pattern, it’s an issue with orphan instances. Newtypes have other uses (e.g. contracts, type-safety for integers and othe
by armchairhacker 3y ago
This isn’t an issue with the “newtype” pattern, it’s an issue with orphan instances. Newtypes have other uses (e.g. contracts, type-safety for integers and other data which has specific meaning). This is just using the newtype pattern to get around the fundamental issue, which is that you can’t define a third-party instance for a third-party type.
Personally, I’d like Rust to have “selectable” implementations, which are named and must be explicitly imported, and explicitly “applied” if there are multiple in scope. Selectable implementations always override regular implementations, so you can also replace the library’s provided implementation if it’s buggy or not what you wanted. I don’t even think there’s an RFC for this though…
Aside: newtype isn’t even Rust-specific. It goes to show how popular Rust is and how much Rustaceons love type safety, that when you search “newtype pattern”, the first results are all Rust. The keyword “newtype” comes from Haskell, which also has the orphan rule and associated issues, but at least lets you disable it with a GHC rule. And a zero-cost wrapper is something you can do in Swift, Kotlin, C++, and even C, and the general newtype pattern (although not necessarily zero-cost) is something you can do in practically any typed language, even untyped ones like JavaScript if you consider runtime exceptions ok (use a struct with the custom type name as the field name).