英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论