Go Tour练习:错误处理:使用Sprintf和%f来避免无限递归。

huangapple go评论84阅读模式
英文:

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

无限循环的情况仅适用于 vsxXq

请参考这里: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

huangapple
  • 本文由 发表于 2017年4月17日 19:43:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/43450813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定