go - fmt.Println calling Error instead of String() -
i have code
package main import ( "fmt" "math" ) type errnegativesqrt float64 func (s errnegativesqrt) string() string { return fmt.sprintf("%f", float64(s)) } func (e errnegativesqrt) error() string { return fmt.sprintf("cannot sqrt negative number: %v", float64(e)) } func sqrt(x float64) (errnegativesqrt, error) { if x < 0 { e := errnegativesqrt(x) return e, e } else { return errnegativesqrt(math.sqrt(x)), nil } } func main() { fmt.println(sqrt(2)) fmt.println(sqrt(-2)) }
and output of code is
cannot sqrt negative number: 1.4142135623730951 <nil> cannot sqrt negative number: -2 cannot sqrt negative number: -2
when have implemented stringer interface errnegativesqrt, why fmt.println invoking error() method instead of string() method?
i new go, might missing obvious.
the documentation states how value converted string:
if operand implements error interface, error method invoked convert object string, formatted required verb (if any).
if operand implements method string() string, method invoked convert object string, formatted required verb (if any).
the error
interface comes before stringer
.
a more idiomatic way write function is:
func sqrt(x float64) (float64, error) { if x < 0 { return 0, errnegativesqrt(x) } return math.sqrt(x), nil }
Comments
Post a Comment