sumtype-go is a CLI tool designed to facilitate the creation and management of sum types (aka union types) in Go. This tool simplifies the process of generating boilerplate code for discriminated union types, making it easier to work with its variants in Go.
To define this sum type:
typeUser=Anonymous|MemberStringTime|AdminString
write this Go type definition, e.g. indeclaration.go
typeUserVariantsstruct {// be sure to suffix the name with `Variants`Anonymousfunc()Memberfunc(emailstring,since time.Time)Adminfunc(emailstring)}Execute this command to generateUser type from yourUserVariants struct
go install github.com/choonkeat/sumtype-go@v0.4.1# to installsumtype-go -input declaration.go
To generatedeclaration.boilerplate.go and start usingUser!
users:= []User{Anonymous(),// this returns a `User` valueMember("Alice",time.Now()),// this also returns a `User` valueAdmin("Bob"),// this also returns a `User` value}and we can pattern matchUser values and return a different value depending on pattern matched variant
userString:=UserMap(user,UserVariantsMap[string]{Anonymous:func()string {return"Anonymous coward"},Member:func(emailstring,since time.Time)string {returnemail+" (member since "+since.String()+")"},Admin:func(emailstring)string {returnemail+" (admin)"},})ordo different things depending on pattern matched variant
funcSendReply(uUser,commentComment) {u.Match(UserVariants{Anonymous:func() {// noop},Member:func(emailstring,since time.Time) {sendEmail(email,comment)},Admin:func(emailstring) {sendEmail(email,comment)},})}Refer toexample/gosumtype_1_*.go
We support generics too. e.g. the classicResult type
typeResult x a=Err x|Ok a
can be defined as
typeResultVariants[x,aany]struct {Errfunc(errx)Okfunc(dataa)}Same thing, after executingsumtype-go to generate the.boilerplate.go file, you can usethe generatedResult like this
results:= []Result[string,int]{Err[string,int]("Oops err"),// this returns a `Result` valueOk[string,int](42),// this also returns a `Result` value}fori,result:=rangeresults {HandleResult(i,result)// implement your own `func HandleResult(int, Result[string, int])`}Refer toexample/result_1_*.go
To installsumtype-go, ensure you have Go installed on your system, and then run the following command:
go install github.com/choonkeat/sumtype-go@v0.4.1
After installation, you can start usingsumtype-go by invoking it from the command line.
$ sumtype-go -hUsage of sumtype-go: -input string Input file name -pattern-match string Name of the pattern match method (default "Match") -suffix string Suffix of the struct defining variants (default "Variants")
Here's a basic example of how to use it:
sumtype-go -input example/gosumtype_1_declaration.go