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?
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.gofile, thegotostatement is used:The
gotoin this case saves us from introducing another (boolean) variable used just for control-flow, checked for at the end. In this case, thegotostatement makes the code actually better to read and easier follow (quite in contrary to the argument againstgotoyou mentioned).Also note, that the
gotostatement 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.