3

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
}
5
  • 4
    Nope. Why are you ignoring errors? Commented Nov 17, 2012 at 1:23
  • 1
    This (internal) function exists only to make my code shorter. It is very unlikely to ignore an error in my case. But this should be a general example and not a "how to ignore errors with concise syntax" example ;-) Commented Nov 17, 2012 at 1:26
  • 7
    If you don't think there could be an error there, I'd recommend capturing it and panicking if you're wrong. You will otherwise just have confusion when an actual error occurs and you've covered it up because you're sure it can't happen. Commented Nov 17, 2012 at 4:28
  • What are you looking for as a “better way”? What is it that you don’t like here? Commented Nov 17, 2012 at 10:38
  • 4
    The second return value of utf.DecodeRuneInString is the rune length, not an error. An error condition is actually returned in the first value as the constant utf8.RuneError. Throwing away the length is fine if you want only a single rune. If you wish to then obtain the next rune though, the length could come in handy for the expression s[length:]. Commented Nov 17, 2012 at 14:27

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.