Skip to content

Instantly share code, notes, and snippets.

@zeekay
Last active August 29, 2015 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeekay/8704100 to your computer and use it in GitHub Desktop.
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.
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