英文:
Should err.Error() be used in string formatting?
问题
这个字符串格式化很好地工作:
err := foo()
if err != nil {
fmt.Printf("调用时,foo返回了'%s'\n", err)
}
在这种情况下,调用err.Error()
有什么好处吗?
fmt.Printf("调用时,foo返回了'%s'\n", err.Error())
英文:
This string formatting works just fine:
err := foo()
if err != nil {
fmt.Printf("foo returned '%s' when called\n", err)
}
Is there any merit do calling err.Error()
in this context?
fmt.Printf("foo returned '%s" when called\n", err.Error())
答案1
得分: 5
两个版本都完全没问题。
fmt包对错误接口有特殊支持(从这个链接向下滚动几屏):
- 如果操作数实现了错误接口,将调用Error方法将对象转换为字符串,然后按照所需的动词格式化。
你的第二个版本可能会运行得更快,因为它可以避免大部分fmt包的特殊断言,但在大多数情况下,差异不会明显。
一般来说,你应该更倾向于第一个版本,它更易读,尤其是在有更多参数的情况下。
英文:
Both versions are completely fine.
The fmt package has special support for the error interface (scroll down a couple screens from this link):
> 4. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).
Your second version will probably run faster as it can avoid most of the special assertions the fmt package does, but the difference shouldn't be noticeable in most cases.
In general you should probably prefer the first version, which is more readable, especially with more arguments.
答案2
得分: 1
如果err
实现了Error
接口,那么当使用有效的格式动词(如%s
)时,将隐式调用Error()方法。有关此内容的更多信息,请参阅fmt的文档。
英文:
If err
implements the Error
interface, then the Error() method will be invoked implicitly when using a valid format verb such as %s
. The documentation for fmt has more on this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论