为什么在Error()方法内调用fmt.Sprint(e)会导致无限循环? [英] Why would a call to fmt.Sprint(e) inside the Error() method result in an infinite loop?
问题描述
我正在通过旅行" 教程.
我想检查一下这个问题的答案:
I would like to check the answer to this question:
注意:在
Error
方法内对fmt.Sprint(e)
的调用将发送 程序陷入无限循环.您可以通过转换来避免这种情况e
首先:fmt.Sprint(float64(e))
.为什么?
Note: a call to
fmt.Sprint(e)
inside theError
method will send the program into an infinite loop. You can avoid this by convertinge
first:fmt.Sprint(float64(e))
. Why?
我相信这是因为调用Sprint
函数时,由于错误为非nil,将再次调用Error function()
,依此类推,从而导致无限循环.
I believe this is because when the Sprint
function is called, since the error is non-nil, the Error function()
will again be called, and so forth, resulting in an infinite loop.
推荐答案
fmt.Sprint(e)
将调用e.Error()
将值e
转换为string
.如果Error()
方法调用fmt.Sprint(e)
,则程序将递归直到内存不足.
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.
您可以通过将e
转换为没有String
或Error
方法的值来中断递归.
You can break the recursion by converting the e
to a value without a String
or Error
method.
这篇关于为什么在Error()方法内调用fmt.Sprint(e)会导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!