Last active
August 29, 2015 13:55
-
-
Save zeekay/8704100 to your computer and use it in GitHub Desktop.
Go error handling using switch statement to "pattern match" against return value(s) of function.
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 "fmt" | |
// Error | |
type notSquared struct { | |
number int | |
} | |
func (e notSquared) Error() string { | |
return fmt.Sprintf("Can't square %v for some inexplicable reason?", e.number) | |
} | |
// We square? Only to a point... | |
func square(x int) (int, error) { | |
// We can't even begin to compute integers this large | |
if x > 10 { | |
return 0, notSquared{x} | |
} | |
return x * x, nil | |
} | |
func main() { | |
// Loop over some numbers and square them, but watch out for errors! | |
for i := 0; i < 42; i++ { | |
// Variables scoped to switch expression, can be used in case statements. | |
total, err := square(i); switch { | |
// Handle error case | |
case err != nil: | |
panic(err) | |
// Numbers that boggle our minds | |
case total < 10: | |
fmt.Println("such numbers", total) | |
default: | |
fmt.Println("wow") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment