The goal of this experiment is to try and implement the minimum requirements for the existence of a generic-style Option
type in Go, similar to what we know from other languages, such as Java or Rust.
Provide a fluent approach to error handling in Go which focuses on highlighting the "happy path", while being 100% idiomatic with Go's error handling convention.
NOTE: The core type is an interface called Option
, having a single requirement:
type Option[T any] interface {
Res() (T, error)
}
This makes it easy for consumers to implement an Option
in whichever ways they see fit.
There are two other important cases here, provided as simple package-level functions:
func Try[T any](val T, err error) Option[T]
Analogous to an Option
constructor, this function can directly take the result/error pair coming from a standard Go function, and produce an Option
instance
The second one is Unwrap
:
func Unwrap[T, K any](o Option[T], fn func(T) (K, error)) Option[K]
Unwrap
is where the fun with optionals happens. It would take an Option
instance, as well as a continuation function, resulting in a new Option
instance. Depending on whether the continuation function returns a value or an error, the new Option
instance may serve as a fast-track error propagator in long call chains (see the example).
NOTE: Why is Unwrap
a package function and not an Option
method?
Indeed, it would have been much more convenient to have Unwrap
be a method on an already created Option
instance. Howeve, at the moment, there is a limitation of the current implementation of generic type parameters. For the same reason, func(T) (K, error)
cannot be extracted into its own convenience type that implements Option
.
Improvement suggestions are more than welcome.