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 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏