4 ms·
Absolutely https://doc.rust-lang.org/std/ops/trait.Index.html https://doc.rust-lang.org/std/ops/trait.Index.html https://github.com/rust-unofficial/patterns/b
by Inityx 8y ago
Absolutely
https://doc.rust-lang.org/std/ops/trait.Index.html https://doc.rust-lang.org/std/ops/trait.Index.html
https://github.com/rust-unofficial/patterns/blob/master/patterns/newtype.md https://github.com/rust-unofficial/patterns/blob/master/patt...
- jonathanstrange 8y agoOr they could just implement integer subtypes like Ada has since 1983, but it seems that Rustaceans prefer to write boilerplate instead.
- kibwen 8y agoAda's integer subtypes are newtypes, but you don't need integer subtypes to have newtypes. Furthermore, newtypes are applicable to more than just integers; e.g. one might newtype String to represent an HTTP header.
- jonathanstrange 8y agoThat's incorrect. Ada has subtypes and new types for scalars and they behave differently. For example, a new integer type is: type MyInteger is integer; declares a new integer type that needs to be explicitly converted to any other integer type. You can also declare a new range integer type as in type MyPositive is integer range 1 .. Integer'Last; But you can also delcare integer and float subtypes: subtype Day_Number is integer range 1 .. 31; or (a bit pointless) subtype MyInt is integer; The difference between new types and subtypes is that no operations of the base type are defined for the new type since it's an entirely new type. A subtype on the other hand allows the operations of the base type, and their range is checked at compile time if possible and runtime if necessary. In addition to this, Ada also has modular integer types, real types, floating point types, fixed point types, and decimal types in the numeric type system and all of them can be subtyped. Of course, you can create a new type for any other type in Ada as well, but that's not what I meant when I was talking about integer subtypes.
- dilap 8y agohow would you use it in practice? i'm guessing, but seems like it would be somewhat heavyweight. does anyone end up doing this, or just using raw ints? thinking in comparison of something like go, where you'd just do > type NodeIndex int
- Inityx 8y agoNewtypes are actually zero overhead abstractions; one prominent example of Newtype is the structs Instant and Duration from std::time: https://doc.rust-lang.org/std/time/index.html https://doc.rust-lang.org/std/time/index.html
- dilap 8y agoah, i meant heavyweight (middle-weight, maybe) in terms of programmer-effort / ergonomics. i know rust is all about zero-runtime-cost abstractions :-)