This is a no nonsense zero dependency generic Optional<T>
implementation for Go.
go get github.com/moveaxlab/go-optional
Return optionals from your repositories:
package repository
import (
"context"
"github.com/moveaxlab/go-optional"
)
type Repository interface {
FindById(ctx context.Context, id string) optional.Optional[Entity]
}
type repository struct {}
func (r *repository) FindById(ctx context.Context, id string) optional.Optional[Entity] {
var entity Entity
var entityWasFound bool
// retrieve the entity in some way
if !entityWasFound {
return optional.Empty[Entity]()
}
return optional.Of(&entity)
}
The use the optionals in your application logic:
package service
func (s *service) DoSomeStuff(ctx context.Context) {
maybeEntity := s.repository.FindById(ctx, "1")
if maybeEntity.IsPresent() {
// we have the entity!
entity := maybeEntity.Get()
}
}
The Optional
type offers these methods:
IsPresent
returns true if there is a value in the optionalGet
returns the value contained in the optional, and panics if it's emptyOrElseGet
accepts a function in input, and returns the value contained in the optional if present, or the result of the function otherwiseOrElsePanic
returns the value contained in the optional if present, or panics with a custom error passed in inputIfPresent
runs the function passed as argument if the value is present, passing it the value contained in the optionalIfPresentOrElse
behaves likeIfPresent
for the first argument, but calls the function passed as second argument if the optional is empty