Created
June 25, 2020 03:31
-
-
Save polynomialspace/ebdc11ca479ad14a17c965c6ab5aee2b to your computer and use it in GitHub Desktop.
Attempting to do optional type stuff in Go2 and doing a terrible job at it
This file contains 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" | |
) | |
type Optional(type T) struct { | |
p *T | |
} | |
func (o Optional(T)) IsSome() bool { | |
return o.p != nil | |
} | |
func (o Optional(T)) IsNone() bool { | |
return o.p == nil | |
} | |
func (o Optional(T)) Or(v T) T { | |
if o.IsNone() { | |
return v | |
} | |
return *o.p | |
} | |
func (o Optional(T)) Val() T { | |
var zero T | |
return o.Or(zero) | |
} | |
/* Broken ? | |
func (o Optional(T)) Map(f func(T) Optional(T)) Optional(T) { | |
if o.p == nil { | |
var zero Optional(T) | |
return zero | |
} | |
return f(*o.p) | |
} | |
*/ | |
func Some(type T) (v T) Optional(T) { | |
return Optional(T) { &v } | |
} | |
func main() { | |
iopt := Some(123) | |
none := Optional(int){} | |
fmt.Println(none.IsNone(), none.IsSome(), none.Val(), none.Or(1)) | |
fmt.Println(iopt.IsNone(), iopt.IsSome(), iopt.Val(), iopt.Or(1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment