Created
February 27, 2018 19:54
-
-
Save dimiro1/ab65d86b9c8b0959f9d64ef15cc6631c to your computer and use it in GitHub Desktop.
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 ( | |
"errors" | |
"fmt" | |
) | |
// Person is a demo struct | |
type Person struct { | |
Name string | |
} | |
// UnwrapPersonError accepts an interface and an error and returns a Person and an error | |
func UnwrapPersonError(i interface{}, err error) (Person, error) { | |
if err != nil { | |
return Person{}, err | |
} | |
p, ok := i.(Person) | |
if !ok { | |
return Person{}, errors.New("the given interface is not an Person") | |
} | |
return p, nil | |
} | |
// UnwrapPerson accepts an interface and returns a Person and an error | |
func UnwrapPerson(i interface{}) (Person, error) { | |
return UnwrapPersonError(i, nil) | |
} | |
func main() { | |
p, err := UnwrapPerson(func() interface{} { | |
return Person{ | |
Name: "Claudemiro", | |
} | |
}()) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(p) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment