英文:
Go Tour Exercise: Errors: using Sprintf with %f to avoid infinite recursion
问题
我正在通过Go教程进行学习,在错误练习中提到,在Error函数中调用Sprint(f)会导致一个问题,即无限循环。为什么会发生这种情况在这里有解释:https://stackoverflow.com/questions/27474907/error-infinite-loop
然而,在我的第一个实现中,我使用了带有%f占位符的Sprintf:
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}
这似乎避免了这个问题,我想知道这是因为%f占位符期望一个浮点数,所以它强制将e作为浮点数处理?教程提到赋值需要显式转换,但我认为这不会影响到这种情况?
或者我完全错了,这里还有其他情况?
英文:
I'm working through the Go tour and in the Errors exercise it mentions that calling Sprint(f) in your Error function will result in an issue, which is an infinite loop. Why this occurs is explained here: https://stackoverflow.com/questions/27474907/error-infinite-loop
In my first implementation though I used Sprintf with the %f verb:
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}
This seems to avoid the issue and I was wondering if this is because the %f verb is expecting a float so it forces it to treat e as a float? The tour mentioned that assignment requires explicit conversion, however I assume that doesn't effect this case?
Or am I completely off the mark and something else is going on here?
答案1
得分: 4
无限循环的情况仅适用于 v
、s
、x
、X
和 q
。
请参考这里:https://github.com/golang/go/blob/6f51082da77a1d4cafd5b7af0db69293943f4066/src/fmt/print.go#L615
英文:
That infinite loop case applies only to v
, s
, x
, X
, and q
.
See here: https://github.com/golang/go/blob/6f51082da77a1d4cafd5b7af0db69293943f4066/src/fmt/print.go#L615
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论