Search code examples
gogoto

Why does Go have a "goto" statement?


I was surprised to find that Go 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, and that functions or methods are always a better way of controlling flow.

I must be missing something. Why did Google include it?


Solution

  • When we actually check the source code of the Go 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.