Created
July 13, 2015 06:02
-
-
Save jonmorehouse/96e6eae1d90ff83ae663 to your computer and use it in GitHub Desktop.
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" | |
"math/rand" | |
"time" | |
) | |
type ErrorA struct {} | |
func (e *ErrorA) Error() string { return "error a" } | |
type ErrorB struct {} | |
func (e ErrorB) Error() string { return "error b" } | |
func GetError() error { | |
now := time.Now().UnixNano() | |
r := rand.New(rand.NewSource(now)) | |
if r.Int() % 2 == 0 { | |
return &ErrorA{} | |
} else { | |
return ErrorB{} | |
} | |
} | |
func ErrorSwitch() { | |
err := GetError(); | |
switch err.(type) { | |
case nil: | |
fmt.Println("No error") | |
case ErrorB: | |
fmt.Println("error type b") | |
case *ErrorA: | |
fmt.Println("error type a") | |
case error: | |
fmt.Println("generic error") | |
} | |
} | |
func main() { | |
ErrorSwitch() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment