Last active
August 19, 2020 21:49
-
-
Save moaible/fce588e695b4abf00ecba6ddfc754a90 to your computer and use it in GitHub Desktop.
go2go: Optional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "github.com/moaible/goptional" // yet not repository | |
| ) | |
| func main() { | |
| var baseValue = 1 | |
| var var1 *int = nil | |
| var var2 *int = &baseValue | |
| op1 := goptional.New(var1) | |
| op2 := goptional.New(var2) | |
| var t, f bool = true, false | |
| var ret *bool | |
| op1.If(func(v *int) { | |
| fmt.Println("1: Presented", *v) | |
| }).OrElse(func() { | |
| ret = &f | |
| fmt.Println("1: Not Presented") | |
| }) | |
| fmt.Println(*ret) | |
| fmt.Println(*op1.ValueOr(var2)) | |
| op2.If(func(v *int) { | |
| ret = &t | |
| fmt.Println("2: Presented", *v) | |
| }) | |
| fmt.Println(*ret) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package optional | |
| import ( | |
| "reflect" | |
| ) | |
| type Optional(type T interface{}) struct { | |
| value interface{} | |
| } | |
| type OptionalEmpty(type T interface{}) struct {} | |
| func New(type T interface{})(value T) *Optional(T) { | |
| return &Optional(T){ | |
| value: &value, | |
| } | |
| } | |
| func (o *Optional(T)) Value() T { | |
| return *o.value.(*T) | |
| } | |
| func (o *Optional(T)) Has() bool { | |
| // FIXME: don't want to use refrect if possible | |
| return !reflect.ValueOf(*o.value.(*T)).IsNil() | |
| } | |
| func (o *Optional(T)) ValueOr(option T) T { | |
| if o.Has() { | |
| return *o.value.(*T) | |
| } else { | |
| return option | |
| } | |
| } | |
| func (o *Optional(T)) If(presenting func(T)) *OptionalEmpty(T) { | |
| if o.Has() { | |
| presenting(o.Value()) | |
| return nil | |
| } | |
| return &OptionalEmpty(T){} | |
| } | |
| func (o *OptionalEmpty(T)) OrElse(presenting func()) { | |
| presenting() | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Click here for a working demo
https://go2goplay.golang.org/p/6CUvn2aXJuU