I am trying to implement this exercise: https://tour.golang.org/methods/20
The solution I come up is:
import (
"fmt"
"math"
)
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.0 {
return 0, ErrNegativeSqrt(x)
}
return math.Sqrt(x), nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
I got stack overflow
error while running this program. However, when I use %g
in the Sprintf
, it works. Can I know why it failed when using %v
?