doucitao2944 2015-01-13 18:14
浏览 188
已采纳

由fmt.Sprint(e)在Error方法内部产生的无限循环

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 (
  "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))
}
  • 写回答

3条回答 默认 最新

  • doushan7997 2015-01-13 18:21
    关注

    It seems it's explained directly is source of fmt package:

    // Is it an error or Stringer?
    // The duplication in the bodies is necessary:
    // setting handled and deferring catchPanic
    // must happen before calling the method.
    

    And than Error() or String() is called.

    What it means is that first error.Error() is called to produce string, which is than once again processed and is printed as string.

    Whether error has method String is irrelevant here. The question is why NegativeSqrt is printed with one method and not the other. Type NegativeSqrt implements both fmt.Stringer and error interfaces so it's up to the implementation of fmt package which of interfaces should be used to get string from NegativeSqrt (since fmt.Sprint takes its parameters by interface{}).

    To illustrate this consider this example:

    package main
    
    import (
        "fmt"
    )
    
    type NegativeSqrt float64
    
    func (e NegativeSqrt) Error() string {
        return ""
    }
    
    func (e NegativeSqrt) String() string {
        return ""
    }
    
    func check(val interface{}) {
        switch val.(type) {
        case fmt.Stringer:
            fmt.Println("It's stringer")
        case error:
            fmt.Println("It's error")
        }
    }
    
    func check2(val interface{}) {
        switch val.(type) {
        case error:
            fmt.Println("It's error")
        case fmt.Stringer:
            fmt.Println("It's stringer")
        }
    }
    
    func main() {
        var v NegativeSqrt
        check(v)
        check2(v)
    }
    

    Executing this gives:

    % go run a.go
    It's stringer
    It's error
    

    This is because in Go type switch behaves just like normal switch, so order of cases matters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 怎么实现不管输入多少字符或者数组或者空格 输出的时候先显示输入的字符数组或者空格再提示输出。输出的结果每个字符后面都带上一个空格
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上
  • ¥15 求解四个变换矩阵中的未知数θ
  • ¥20 Intellij实现web登录界面
  • ¥15 IPQ5018制作烧录固件,boot运行失败(操作系统-linux)(相关搜索:操作系统)(相关搜索:操作系统)
  • ¥20 icefall在librispeech基础上加入个人数据集
  • ¥30 keepalive高可用故障运维配置询问
  • ¥15 求帮助!国家电网内网u盘突然识别不出来了。
  • ¥15 matlab语音变速变调同时实现