Golang中的函数声明 [英] Function declaration in Golang
问题描述
似乎有两种不同的方法可以在Golang中声明一个函数,如下所示:
It seems there are two different ways to declare a function in Golang, like this:
package main
import "fmt"
var someFunc = func(arg string) {
fmt.Println(arg)
}
func main() {
someFunc("Hello")
}
上面的作品.但是,以下方法不起作用:
The above works. However, the below does not work:
package main
import "fmt"
var someFunc = func(arg string) {
fmt.Println(arg)
}
var main = func() {
someFunc("Hello")
}
它将抱怨:
runtime.main: undefined: main.main
那么 func someFunc()
和 var someFunc = func()
之间有什么区别?
So what's the difference between func someFunc()
and var someFunc = func()
?
我发现它的原因可能也是因为我也编写了许多Javascript.在Go语言中,似乎很少有人看到像 var someFunc = func()
这样的函数.在这两个中,我们可以说哪个比另一个更正确吗?
The reason I found this is probably because of I code a lot of Javascript, too. It seems in Go, I rarely see people declaring a function like var someFunc=func()
. Of these two, can we say which one is more correct than the other one?
推荐答案
执行时
var someFunc = func(arg string) {}
您正在为 somefunc
变量分配一个匿名函数.您也可以这样写:
you are assigning an anonymous function to the somefunc
variable. You could also write it like this:
somefunc := func(arg string) {}
创建函数的另一种方法是创建命名函数:
The other way to create a function is to create a named function:
func somefunc(arg string) {}
命名函数只能在顶层声明,而匿名函数可以在任何地方声明.而且 main
具有特殊的含义,在 main
包中必须有一个名为 main
的命名函数,这就是为什么您在第二种情况.
Named functions can only be declared at the top level whereas anonymous functions can be declared anywhere. And main
has a special meaning, there has to be a named function called main
in the main
package, that's why you got an error in the second case.
这篇关于Golang中的函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!