2015-01-13 18:14
浏览 182


According to fortyforty's reply to this question:

fmt.Sprint(e) will call e.Error() to convert the value e to a string. If the Error() method calls fmt.Sprint(e), then the program recurses until out of memory.

You can break the recursion by converting the e to a value without a String or Error 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 (

type NegativeSqrt float64

func (e NegativeSqrt) Error() string {
  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() {

3条回答 默认 最新

相关推荐 更多相似问题