为什么Go有一个“goto”声明 [英] Why does Go have a "goto" statement
问题描述
我必须缺少一些东西。为什么和何时使用'goto'是一个好主意?或者为什么Google包含它?
当我们实际检查Gos源代码时(标准库 ),我们可以看到 goto
s的实际应用情况。
例如,在 math / gamma.go
文件,使用goto语句:
for x < 0 {
if x> -1e-09 {
goto small
}
z = z / x
x = x + 1
}
for x < 2 {
如果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] (x + _gamQ [5])* x + _gamQ [5])* x + _gamQ [6])* x + _gamQ [2])* x + _gamQ [3])* _gamQ [7]
返回z * p / q
小:
如果x == 0 {
return Inf(1)
}
return z /((1 + Euler * x)* x)
}
在这种情况下, goto
避免了引入另一个仅用于控制流的布尔变量,并在最后检查。 在这种情况下, goto
语句使得代码实际上更易于阅读和更容易遵循(与 goto
you said。)
还要注意, goto
语句有一个非常具体的用例。关于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?
When we actually check Gos source code (the standard library), we can see where goto
s 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.
这篇关于为什么Go有一个“goto”声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!