Sum type experiment

109 views
Skip to first unread message

Sina Siadat

unread,
Aug 11, 2020, 10:38:52 AM8/11/20
to golang-nuts
Hi golang-dev :)

I was wondering what would be an idiomatic Go way
to implement a basic sum type in Go. After several
iterations I came up with 2 approaches I will share here.

(1) Group types in an interface

The first approach does not require any new tools
and is statically checked by Go1 compilers.  In
this approach, I group several types by having
them implement a common interface whose sole
purpose is to group those types. Here is an
example:

        type IPv4 [4]byte
        type IPv6 [16]byte
        
        type IP interface {
                GroupTypes(IPv4, IPv6)
        }
        
        func (IPv4) GroupTypes(IPv4, IPv6) {}
        func (IPv6) GroupTypes(IPv4, IPv6) {}

That's it. The GroupTypes method implementations
are no-op.  Their purpose is only to implement the
IP interface.

Now we can leverage Go's static type checking to
make sure we never assert an IP to anything other
than IPv4 and IPv6.  For example, this code will
error:

        var ip IP
        switch ip.(type) {
        case string: // string does not implement IP
        }

I wrote a simple generator and pushed in here:

(2) Type list

The second design is basically the same as the Sum
type (defined in dev.go2go). However, I wanted it
to work with Go1 code, so I decided to specify the
type list as a special comment (eg // #type T1, T2)
and forked dev.go2go to convert that commented type
list to an actual go2go type list.  The code is
available in

Let me know what you think :)

sina

Ian Davis

unread,
Aug 11, 2020, 10:46:42 AM8/11/20
to golan...@googlegroups.com

On Tue, 11 Aug 2020, at 3:38 PM, Sina Siadat wrote:
Hi golang-dev :)

I was wondering what would be an idiomatic Go way
to implement a basic sum type in Go. After several
iterations I came up with 2 approaches I will share here.

You may be interested in the discussions on https://github.com/golang/go/issues/19412 if you haven't already seen them.

Ian

Sina Siadat

unread,
Aug 11, 2020, 11:47:21 AM8/11/20
to golang-nuts
Thanks for the link, Ian. I will have a look at it :)
Reply all
Reply to author
Forward
0 new messages