功能内的功能
I came across some code which uses functions like the following:
func main() {
...
X:
...
}
I'm confused as to what this does. Here is an example I created to try and mess around and see what's happening, but I don't completely understand what K
is, is it a closure? A lambda function?
package main
import "fmt"
func main() {
for i:=0; i<10; i++ {
K: for j:=0; j<10; j++{
if i*j == 81 {
fmt.Printf("%v,%v", i, j)
break;
} else {
continue K;
}
}
}
}
I'm very new to Go and functional programming too so I'm trying to understand this notion.
It's a label statement. You use it with goto
, break
or continue
.
From docs:
It is illegal to define a label that is never used. In contrast to other identifiers, labels are not block scoped and do not conflict with identifiers that are not labels. The scope of a label is the body of the function in which it is declared and excludes the body of any nested function.
They are useful in cases where you need to change the flow in some way, ie.
K: for i:=0; i<10; i++ {
for j:=0; j<10; j++{
if (somefunction(j)) {
continue K; // stops this for, and continue the outer one
} else if (otherfunction(i, j)) {
break K; // stops the outer loop
}
....
}
}
Those are not functions, but labeled statements in golang.
The labeled statements can be used as targets for goto
break
continue
etc.