函数内部的函数

huangapple go评论87阅读模式
英文:

Functions within functions

问题

我遇到了一些使用以下函数的代码:

func main() {

	...
	X:
		...

}

我对这个函数的作用感到困惑。这是我创建的一个示例,我试图进行一些尝试并查看发生了什么,但我不完全理解 K 是什么,它是一个闭包吗?一个 lambda 函数吗?

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;
			}
		}
	} 

}

我对 Go 和函数式编程都非常陌生,所以我正在努力理解这个概念。

英文:

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 &quot;fmt&quot;

func main() {
	for i:=0; i&lt;10; i++ {
		K: for j:=0; j&lt;10; j++{
			if i*j == 81 {
				fmt.Printf(&quot;%v,%v&quot;, i, j)
				break;
			} else {
				continue K;
			}
		}
	} 

}

I'm very new to Go and functional programming too so I'm trying to understand this notion.

答案1

得分: 7

这是一个标签语句。你可以与gotobreakcontinue一起使用它。

根据文档

定义一个从未使用过的标签是非法的。与其他标识符不同,标签不是块作用域的,也不会与非标签的标识符冲突。标签的作用域是声明它的函数体,不包括任何嵌套函数的函数体。

在某些情况下,它们非常有用,可以改变程序的流程,例如:

K: for i:=0; i<10; i++ {
    for j:=0; j<10; j++{
        if (somefunction(j)) {
            continue K; // 停止当前的循环,并继续外层循环
        } else if (otherfunction(i, j)) {
            break K; // 停止外层循环
        }
        ....
    }
}
英文:

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&lt;10; i++ {
    for j:=0; j&lt;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
        }
        ....
    }
}

答案2

得分: 1

这些不是函数,而是在Go语言中的标记语句。

这些标记语句可以作为gotobreakcontinue等语句的目标。

英文:

Those are not functions, but labeled statements in golang.

The labeled statements can be used as targets for goto break continue etc.

huangapple
  • 本文由 发表于 2016年12月1日 21:38:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/40912149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定