題目:
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:
上述代碼如果直接運(yùn)行的話會導(dǎo)致infinite loop显拜,因?yàn)?fmt.Sprintf("cannot Sqrt negative number: %v", e)
會不斷調(diào)用e.Error()
轉(zhuǎn)換成string
寝贡,
所以fmt.Sprintf("cannot Sqrt negative number: %v", e)
應(yīng)改為fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
orfmt.Sprintf("cannot Sqrt negative number: %f", e)
泳唠。