This is quite clever but you really don’t want to have to define types for all of the currencies in use where most people deal with one or few at most. Worse, new currencies may come into existence at any time. And consider securities such as stocks, bonds etc. which have some similar operations but if you buy shares of different companies, they must be kept separate. Accidentally adding Apple shares to IBM shares should be flagged. New companies get listed all the time so you really want an ability to create and use dynamic instances of a generic type. In the absence of such you can always write verification code to avoid such mistakes. I was just musing that it sure would be nice to be able to have the compiler do such checking.
> On Nov 29, 2018, at 7:59 PM, Ian Denhardt <i...@zenhack.net> wrote: > > Quoting Bakul Shah (2018-11-29 22:13:45) > >> I doubt go2 will get generics flexible enough for this! > > It can actually already pull much of this off, and you don't even need the > contracts part of the draft. E.g: > > // Type 'Money' represents a monetary value. The Currency type parameter > // is unused at runtime, but serves to prevent mixing up different > // currencies: > type Money(type Currency) int64 > > // These types used as the parameter for 'Money'. They are never used as > // values, just as part of this trick with the type system -- because of > // this you'll sometimes hear them referred to as "phantom types". > type USD struct{} > type EUR struct{} > type GBP struct{} > // ... > > var m1 Money(USD) = 5 > var m2 Money(USD) = 10 > var m3 Money(EUR) = 2 > > m1 + m2 // ok > m2 + m3 // type error: Money(USD) vs. Money(EUR) -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.