普通网友
2012-06-16 15:58
浏览 117
已采纳

Go为什么有“ goto”语句

Google's Go language is a new language. Therefor I was surprised to find that it has a 'goto' statement. I've always been taught that 'goto' statements are a thing of the past and evil for it occludes the actual flow of a program. Function (or methods if you will) are always a better way of controlling flow.

I must be missing something. Why and when is using 'goto' a good idea? Or why did Google include it?

图片转代码服务由CSDN问答提供 功能建议

Google的Go语言是一种新语言。 因此,我惊讶地发现它具有“ goto” 语句。 一直以来,我一直被教导说“ goto”语句已经成为过去,并且因为它遮挡了程序的实际流程,因此变得邪恶。 函数(或方法,如果可以的话)始终是控制流量的更好方法。

我肯定缺少一些东西。 为什么和何时使用“ goto”是个好主意? 还是Google为什么要包含它?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • duanposhi3641 2012-06-16 17:24
    最佳回答

    When we actually check Gos source code (the standard library), we can see where gotos are actually well applied.

    For example, in the math/gamma.go file, the goto statement is used:

      for x < 0 {
        if x > -1e-09 {
          goto small
        }
        z = z / x
        x = x + 1
      }
      for x < 2 {
        if x < 1e-09 {
          goto small
        }
        z = z / x
        x = x + 1
      }
    
      if x == 2 {
        return z
      }
    
      x = x - 2
      p = (((((x*_gamP[0]+_gamP[1])*x+_gamP[2])*x+_gamP[3])*x+_gamP[4])*x+_gamP[5])*x + _gamP[6]
      q = ((((((x*_gamQ[0]+_gamQ[1])*x+_gamQ[2])*x+_gamQ[3])*x+_gamQ[4])*x+_gamQ[5])*x+_gamQ[6])*x + _gamQ[7]
      return z * p / q
    
    small:
      if x == 0 {
        return Inf(1)
      }
      return z / ((1 + Euler*x) * x)
    }
    

    The goto in this case saves us from introducing another (boolean) variable used just for control-flow, checked for at the end. In this case, the goto statement makes the code actually better to read and easier follow (quite in contrary to the argument against goto you mentioned).

    Also note, that the goto statement has a very specific use-case. The language specification on goto states that it may not jump over variables coming into scope (being declared), and it may not jump into other (code-)blocks.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题