普通网友 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?

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R