英文:
return only a single of multiple return values in Go
问题
有没有更好的方法只返回多个返回值中的一个?
英文:
Is there a better way to return only a single of multiple return values?
func makeRune(s string) (r rune) {
r, _ = utf8.DecodeRuneInString(s)
return
}
答案1
得分: 7
是的。你应该为为什么要这样做添加一个注释。因为这样做的动机常常是错误的,人们会对此提出质疑,就像他们在对你的原始帖子的评论中所做的那样。如果你有写一个函数来丢弃返回值的充分理由,请在注释中进行解释。也许你可以这样写:
// makeRune辅助函数允许函数链接。
func makeRune(s string) (r rune) {
// 丢弃长度返回值。在这个程序的所有用例中,只需要解码第一个符文。
r, _ = utf8.DecodeRuneInString(s)
return
}
这也有助于代码审查,遵循“如果注释和代码不一致,那么两者都可能是错误的”的经验法则。如果不需要函数链接,那么函数的整个目的就值得怀疑。如果你的注释暗示你认为你正在丢弃一个错误值,那就是一个警示信号。如果你的注释暗示你认为s只能包含一个符文,那也是一个警示信号。根据我上面的示例注释,我可能会阅读我所写的内容,并决定将函数命名为firstRune会更好。这样更具体的含义,并避免了暗示与Go的make函数类似的语义。
英文:
Yes. You should add a comment for why you are doing this. Because motives for doing this are often misguided, people will question it, as they have in the comments to your OP. If you have good reason for writing a function to toss a return value, justify it in a comment. Perhaps you could write,
// makeRune helper function allows function chaining.
func makeRune(s string) (r rune) {
// toss length return value. for all use cases in this program
// only the first rune needs to be decoded.
r, _ = utf8.DecodeRuneInString(s)
return
}
This also helps code review by following the rule of thumb, "if the comments and the code disagree, both are probably wrong." If function chaining was not required, the function's whole purpose is questionable. If your comments suggested you thought you were tossing an error value, that would be a red flag. If your comments suggested you thought that s could only contain a single rune, that would be a red flag as well. Given my example comments above, I might read what I had written and decide the function would be better named firstRune. That carries more specific meaning and avoids suggesting semantics similar to that of the Go make function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论