Re:Toward Go 2
by I_am_tiberius on Thursday July 13, 2017 @03:19PM
(#14764306)
Thanks for that information. I had thought enums can only be used as named types. Good to know they can hold data as well. I had though of that struct as well (ok, not in that professional way with types as constants and iota:-)) but found it a bit annoying that I have to store a type myself although the type itself should already have the type information somewhere itself - consequently that information is stored reduntantly. But I'll definitely try that. Thanks.
> I had thought enums can only be used as named types. Good to know they can hold data as well.
That depends on the language, and enums being sum types also depends on the language.
* Rust and Swift enums are sum types (they can hold data and every variant can hold different stuff), there is also a ton of (mostly functional) languages with sum types not called enum: Haskell, F#, OCaml, … there are also languages which replicate them via other structures (sealed classes in Kotlin, case classes in Scala).
* java enums (a bare "enum" is the C one) can hold data but every variant must hold data of the same type so you'd need up/down casts
* C++, C# and C enums can't hold data
Go does not have enums.
C++17 has support for sum types via std::variant.
Re:Toward Go 2
by matt_kantor on Friday July 14, 2017 @10:21AM
(#14769985)
Minor nitpick: case classes in Scala are product types, not sum types. I think you meant "sealed traits".
The combination of both really.
FWIW generics wouldn't help you with that, "sum types" would. A sum type is a souped-up enum which can store associated data alongside the "enum tag", so you can have e.g.
and at runtime you ask which "value" is in your enum: (and in most languages the compiler will yell at you if you forget one of the variants).So for your use case you'd have e.g.
> I played around with interface and reflect.TypeOf but lost too much performance compared to just storing everything in a string.Maybe try a struct with an explicit tag rather than reflection? e.g.
and then you can I'd expect reflect.TypeOf to be very expensive, this is a check + a cast.