DEV Community

moznion
moznion

Posted on

Published go-optional: Go's Generics friendly optional/option type library

I've published go-optional, which is a library that provides Go's Generics friendly option/optional type functions.

GitHub logo moznion / go-optional

A library that provides Go Generics friendly "optional" features.

This library provides "typed option" by using generics, it implies this would be a replacement of "nil checking" for the purpose of value existence inspection. This has the pros of strong typing.

You can see the basic usage of this in the synopsis and examples.
Currently, this brings the following utility option functions:

  • IsSome()
  • IsNone()
  • Take()
  • TakeOr()
  • TakeOrElse()
  • Filter()
  • Map()
  • MapOr()
  • Zip()
  • ZipWith()
  • Unzip()
  • UnzipWith()

This library uses Go's under-developing feature "Generics", so if you'd like to try this library, you may have to use the edge of go runtime at this moment (i.e Nov 18, 2021). I suppose gotip would help you to get and install the latest go runtime.
Also you can try this on The Go Playground for gotip: https://gotipplay.golang.org/p/mWGdFIfcK8c

Unfortunately, the Go compiler prohibits putting type parameters on a method so far. For example:

type Something struct {
}

func (s *Something) Echo[V any](v V) V {
    return v
}
Enter fullscreen mode Exit fullscreen mode

at the first glance, this code seems valid syntactically but...

./main.go:6:25: methods cannot have type parameters
./main.go:6:26: invalid AST: method must have no type parameters
Enter fullscreen mode Exit fullscreen mode

the compiler raises the compiling error like the above. This means a method (i.e. a function that has a receiver) cannot have type parameters at present.
Actually, there is a workaround for this by transforming a method to a function like a bellow:

func Echo[V any](s *Something, v V) V {
    return v
}
Enter fullscreen mode Exit fullscreen mode

Therefore, some features (e.g. Map()) are implemented as the function instead of the method in this library.


I wrote this library for my learning the Generics features then I felt Go Generics is almost production-ready, and I believe this library would be also useful :)

Enjoy!

Top comments (0)