doucang6914 2012-11-17 01:20
浏览 408
已采纳

在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条回答 默认 最新

  • doujiongqin0687 2012-11-17 15:21
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失