为什么在Error()方法内调用fmt.Sprint(e)会导致无限循环? [英] Why would a call to fmt.Sprint(e) inside the Error() method result in an infinite loop?

查看:165
本文介绍了为什么在Error()方法内调用fmt.Sprint(e)会导致无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过旅行" 教程.

我想检查一下这个问题的答案:

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 the Error method will send the program into an infinite loop. You can avoid this by converting e 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转换为没有StringError方法的值来中断递归.

You can break the recursion by converting the e to a value without a String or Error method.

这篇关于为什么在Error()方法内调用fmt.Sprint(e)会导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆