Skip to content

Instantly share code, notes, and snippets.

@itsmikeq
Last active August 29, 2015 14:20
Show Gist options
  • Save itsmikeq/b7c516332a63f551b72a to your computer and use it in GitHub Desktop.
Save itsmikeq/b7c516332a63f551b72a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return x, ErrNegativeSqrt(x)
}
return math.Sqrt(x), nil
}
func main() {
if r, err := Sqrt(2); err != nil {
fmt.Println(err)
} else {
fmt.Println(r)
}
if r, err := Sqrt(-2); err != nil {
fmt.Println(err)
} else {
fmt.Println(r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment