Re:Sum Types in Go
by Animats on Friday December 26, 2014 @01:33AM
(#8798270)
A sum type is a type in a language that can have multiple different kinds of values, which themselves may contain values of differing types. To put it in C terms, it is a "union" in a struct with an element that says which member of the union is currently the active element.
That's called a discriminated variant type. Pascal had it, as did Ada and the various Modulas. Rust has something like it, as an extension to enums. In C++ and Go, you can sort of fake it with the subclassing mechanisms.
Go tends to over-use "interface{}" as an "any" type. This adds cost to things like unpacking SQL rows, which come back as "[]interface{}" and then have to be converted to language types item by item. Go could use something built-in mechanism for
err := Pack(Titem, interfaces)
to pack up an item of type T into an array of interfaces, and
err := Unpack(interfaces, Titem)
to unpack one. It's easy to compile hard code for that, but inefficient to dismantle the structure with reflection. It's useful whenever there's marshaling needed - JSON, SQL, XML, etc.
That's called a discriminated variant type. Pascal had it, as did Ada and the various Modulas. Rust has something like it, as an extension to enums. In C++ and Go, you can sort of fake it with the subclassing mechanisms.
Go tends to over-use "interface{}" as an "any" type. This adds cost to things like unpacking SQL rows, which come back as "[]interface{}" and then have to be converted to language types item by item. Go could use something built-in mechanism for
to pack up an item of type T into an array of interfaces, and to unpack one. It's easy to compile hard code for that, but inefficient to dismantle the structure with reflection. It's useful whenever there's marshaling needed - JSON, SQL, XML, etc.