According to fortyforty's reply to this question:
fmt.Sprint(e)
will calle.Error()
to convert the valuee
to astring
. If theError()
method callsfmt.Sprint(e)
, then the program recurses until out of memory.You can break the recursion by converting the
e
to a value without aString
orError
method.
This is still confusing to me. Why does fmt.Sprint(e) call e.Error() instead of String()? I tried using the Stringer interface, this is my code:
package main
import (
"fmt"
"math"
)
type NegativeSqrt float64
func (e NegativeSqrt) Error() string {
fmt.Printf(".")
return fmt.Sprint(e)
}
func (e NegativeSqrt) String() string {
return fmt.Sprintf("%f", e)
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, NegativeSqrt(x)
}
return math.Sqrt(x), nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}