This is a creation in Article, where the information may have evolved or changed.
Copy your Sqrt function from the earlier exercises and modify it to return an error value.
SqrtShould 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 error a by giving it a
Func (e errnegativesqrt) Error () string
Method such that ErrNegativeSqrt(-2).Error() returns "cannot Sqrt negative number: -2" .
Note: a call to inside the method would send the program into an fmt.Print(e) Error infinite loop. You can avoid this by converting first e : fmt.Print(float64(e)) . Why?
Change your Sqrt function to return the ErrNegativeSqrt value when given a negative number.
Package Main
Import (
"FMT"
)
Type errnegativesqrt float64
Func (e errnegativesqrt) Error () string{
Return to FMT. Sprintf ("Cantnot Sqrt negative Number:%v", Float64 (e))
}
Func Sqrt (f float64) (Float64, error) {
If f < 0 {
return 0, errnegativesqrt (f)
}
Z: = f
For I: = 0; I < 10; i++ {
z = (z + f/z)/2
}
Return Z, Nil
}
Func Main () {
If value, err: = Sqrt (-2); Err! = Nil {
Fmt. PRINTLN (ERR)
} else {
Fmt. Println (value)
}
If value, err: = Sqrt (2); Err! = Nil {
Fmt. PRINTLN (ERR)
} else {
Fmt. Println (value)
}
}