go - 为什么在 Error() 方法内调用 fmt.Sprint(e) 会导致无限循环?

标签 go

我正在浏览 "A Tour of Go"教程。

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

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 函数被调用时,由于错误是非零的, Error function() 将再次被调用,等等,导致一个无限循环。

最佳答案

fmt.Sprint(e) 将调用 e.Error() 将值 e 转换为 string。如果 Error() 方法调用 fmt.Sprint(e),则程序会递归直到内存不足。

您可以通过将 e 转换为没有 StringError 方法的值来打破递归。

关于go - 为什么在 Error() 方法内调用 fmt.Sprint(e) 会导致无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54935629/

相关文章:

mongodb - 使用 mgo 省略多个字段

go - 从 net.Conn 检索 uri 路径

unix - 在 go 中获取未安装卷的 BLKID

go - Golang花括号内发生了什么

regex - 具有拉丁字符的 Golang 正则表达式边界

postgresql - Docker-compose Go 应用程序和 Postgres 之间的通信问题

html - 为什么 Revel Web 框架教程应用程序不起作用

go - Go中的列表目录

image - 从HTTP响应正文中检索图像

go - 如果包文件夹中存在多个文件且其中一个文件包含 "package main",如何指定包名称?