题目:
Copy your
Sqrt
function from the earlier exercise and modify it to return anerror
value.
Sqrt
should return a non-nil error value when given a negative number, as it doesn't support complex numbers.
Create a new type type ErrNegativeSqrt float64
and make it an error by giving it a
func (e ErrNegativeSqrt) Error() string
method such thatErrNegativeSqrt(-2).Error()
returns"cannot Sqrt negative number: -2".
</br>
Note: a call tofmt.Sprint(e)
inside theError
method will send the program into an infinite loop. You can avoid this by convertinge
first:fmt.Sprint(float64(e))
. Why?</br>
Change yourSqrt
function to return anErrNegativeSqrt
value when given a negative number.
exercise-errors.go
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %v", e)
}
func Sqrt(x float64) (float64, error) {
if (x < 0) {
return x, ErrNegativeSqrt(x)
}
z := 1.0
for i := 0; i < 10; i++ {
z = z - (z*z - x)/(2*z);
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
Note:
上述代码如果直接运行的话会导致infinite loop,因为 fmt.Sprintf("cannot Sqrt negative number: %v", e)
会不断调用e.Error()
转换成string
,
所以fmt.Sprintf("cannot Sqrt negative number: %v", e)
应改为fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
orfmt.Sprintf("cannot Sqrt negative number: %f", e)
。