Skip to content

Instantly share code, notes, and snippets.

@zh-f
Created June 10, 2020 02:25
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 zh-f/51c67ca8051f23e22dd409f02c01c62a to your computer and use it in GitHub Desktop.
Save zh-f/51c67ca8051f23e22dd409f02c01c62a to your computer and use it in GitHub Desktop.
Solution of Exercise: Errors
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string{
return fmt.Sprintf("cannot Sqrt negative number: %v\n", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return x, ErrNegativeSqrt(x)
}
return 0, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
@zh-f
Copy link
Author

zh-f commented Jun 10, 2020

0 <nil>
-2 cannot Sqrt negative number: -2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment