0

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?

injoy
  • 3,993
  • 10
  • 40
  • 69
  • 1
    Same as https://stackoverflow.com/questions/42600920/runtime-goroutine-stack-exceeds-1000000000-byte-limit-fatal-error-stack-overf and https://stackoverflow.com/questions/39731608/struct-string-implemention-causes-stack-overflow-with-sprintf-flag – JimB Feb 28 '19 at 23:16
  • 1
    Yes, the default formatting checks for both `String()` and `Error()`. From the docs: `4. If an operand implements the error interface, the Error method will be invoked to convert the object to a string` – JimB Feb 28 '19 at 23:19

0 Answers0