Skip to content

Instantly share code, notes, and snippets.

@pirogoeth
Created July 28, 2017 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirogoeth/079bcaf306f835d23002ce3e89737e5a to your computer and use it in GitHub Desktop.
Save pirogoeth/079bcaf306f835d23002ce3e89737e5a to your computer and use it in GitHub Desktop.
I tried ¯\_(ツ)_/¯
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