Created
July 28, 2017 19:27
-
-
Save pirogoeth/079bcaf306f835d23002ce3e89737e5a to your computer and use it in GitHub Desktop.
I tried ¯\_(ツ)_/¯
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 ( | |
"errors" | |
"fmt" | |
"reflect" | |
"time" | |
) | |
type Result struct { | |
value interface{} | |
err error | |
} | |
func (r Result) Error() error { | |
return r.err | |
} | |
func (r Result) Value() interface{} { | |
return r.value | |
} | |
func (r Result) IsValueOfType(cmp interface{}) bool { | |
return reflect.TypeOf(r.value) == reflect.TypeOf(cmp) | |
} | |
func (r Result) WithError(err error) Result { | |
r.err = err | |
return r | |
} | |
func (r Result) WithValue(val interface{}) Result { | |
r.value = val | |
return r | |
} | |
type SomeData struct { | |
Name string | |
Date time.Time | |
} | |
func (s *SomeData) DoThing() { | |
fmt.Printf("Doing a thing for %s\n", s.Name) | |
} | |
func GetData() Result { | |
return Result{}.WithValue(&SomeData{ | |
Name: "Some Data", | |
Date: time.Now(), | |
}) | |
} | |
func GetDataError() Result { | |
return Result{}.WithError(errors.New("There was a problem")) | |
} | |
func main() { | |
var res Result | |
res = GetData() | |
if res.Error() != nil { | |
panic(res.Error()) | |
} | |
if res.IsValueOfType(&SomeData{}) { | |
value := res.Value().(*SomeData) | |
value.DoThing() | |
} | |
fmt.Printf("%#v\n", res.Value()) | |
res = GetDataError() | |
if res.Error() != nil { | |
panic(res.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment