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
}
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
}
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.