Skip to content

Instantly share code, notes, and snippets.

@kjk
Created November 5, 2019 09:13
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 kjk/646f2e936bff82f90b7fbc62f891bf3c to your computer and use it in GitHub Desktop.
Save kjk/646f2e936bff82f90b7fbc62f891bf3c to your computer and use it in GitHub Desktop.
Error handling
// :collection Essential Go
package main
import (
"fmt"
"math"
)
// :show start
func sqrt(n float64) (float64, error) {
if n < 0 {
return 0, fmt.Errorf("invalid argument '%f', must be >= 0", n)
}
return math.Sqrt(n), nil
}
func printSqrt(n float64) {
if res, err := sqrt(n); err == nil {
fmt.Printf("sqrt of %f is %f\n", n, res)
} else {
fmt.Printf("sqrt of %f returned error '%s'\n", n, err)
}
}
func main() {
printSqrt(16)
printSqrt(-16)
}
// :show end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment