包 “main” 和函数 “main”

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

Package "main" and func "main"

问题

我看到的一些示例Go程序都以以下方式开始:

package main

并且有

func main()

包行中的 "main" 和函数行中的 "main" 之间有任何关系吗?我猜应该没有。C/C++ 使用相同的 "main" 入口点。只是想确保一下。我还没有看到任何文档说明 "main" 的使用只是巧合。

英文:

The intro/sample go progs I've seen and experimented with start with

package main

and have

func main()

Is there any relationship between the "main" in the package line and the "main" in the func line? I'm guessing not. C/C++ uses the same "main" entry point. Just want to make sure though. I haven't seen any docs that say the use of "main" is just a coincidence.

答案1

得分: 52

应用程序的入口点是main包中的main函数,如规范所述:

通过将一个名为main包的未导入包与其导入的所有包进行链接,可以创建一个完整的程序,包括传递的包。主包必须具有包名称main并声明一个不带参数且不返回值的函数main

func main() { … }

程序的执行从初始化主包开始,然后调用函数main。当该函数调用返回时,程序退出。它不会等待其他(非主)goroutine完成。

语言规范在这个上下文之外没有给main名称赋予特殊含义。main名称不是保留名称。

在非主包中声明main函数是可以的。在这种情况下,它只是一个名为main的函数。

英文:

The entry point for the application is the main function in the main package as described in the specification:

> A complete program is created by linking a single, unimported package called the main package with all the packages it imports, transitively. The main package must have package name main and declare a function main that takes no arguments and returns no value.
>
func main() { … }
> Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

The language specification does not give special meaning to the name main outside of this context. The name main is not a reserved name.

It's OK to declare a main function in non-main packages. In such cases, it's just a function named main.

huangapple
  • 本文由 发表于 2017年2月20日 06:08:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/42333488.html
匿名

发表评论

匿名网友

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

确定