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]
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)