DEV Community

Denis
Denis

Posted on

Small sum types in Golang

You can model sum types in golang as following

import "github.com/samber/mo"

// tags and their types
type (
    Id    int
    Phone string
    Email string
)

// UserKey is a sum type
type UserKey = mo.Either3[Id, Email, Phone]
Enter fullscreen mode Exit fullscreen mode

I find this implementation to be quite minimal and less clumsy than alternatives. Sure, you don't get nice exhaustive pattern matching. Also, type inference gets in the way when instantiating UserKey (though you can wrap it in constructor functions). But expressing your intent using types still makes your code much more convenient and easier to understand.

Top comments (0)