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.

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

报告相同问题?

悬赏问题

  • ¥50 swiftui @query 报错
  • ¥50 怎么解决刷卡或扫码后,点击软件输入框,win10屏幕键盘不会自动弹出的问题
  • ¥15 如何使用arcgispro的训练深度模型,发现water和nowater精度为0?(相关搜索:深度学习)
  • ¥20 matlab作业不太懂呀有问题能给个代码吗
  • ¥15 自制电路图为何无法驱动ESP01S?
  • ¥15 前端加access数据库
  • ¥15 ARCGIS 多值提取到点 ERROR 999999
  • ¥15 mysql异常断电, [MY-011971] [InnoDB]
  • ¥15 uni.onBluetoothDeviceFound熄屏不运行
  • ¥15 求PHDA糖尿病并发症数据集,有偿