英文:
Is main.go required in a Go project?
问题
没有C语言背景,只有“初学者”级别的Go经验,我正在努力弄清楚main.go
是否真的是必需的,还是只是一种约定。
我想创建一个简单的Web API,但有人可以为我澄清这个问题吗?
英文:
Without a background in C and only "beginner" experience in Go I'm trying to work out whether main.go
is actually required or is just a convention.
I'm looking to create a simple web API but could someone clarify this for me?
答案1
得分: 37
main.go
作为一个文件是不必要的。
然而,对于可执行文件,需要一个带有func main()
的main
包。
你的文件名可以随意命名。
例如:
myawesomeapp.go
package main
func main() {
fmt.Println("Hello World")
}
运行go run myawesomeapp.go
将按预期工作。
英文:
main.go
as a file is not required.
However, a main
package with a func main()
is required for executables.
Your file name can be called whatever you want.
E.g
myawesomeapp.go
package main
func main() {
fmt.Println("Hello World")
}
Running go run myawesomeapp.go
will work as expected.
答案2
得分: 11
对于一个 web 服务器(一个可执行文件),你需要有一个 package main
和一个 func main()
,但它的文件名可以是任何你想要的。根据语言规范:
程序执行
通过将一个名为 main 的单个未导入的包与其导入的所有包进行链接,可以创建一个完整的程序,包括传递的包。主包必须具有包名 main,并声明一个不带参数且不返回值的 main 函数。
func main() { … }
程序的执行从初始化主包开始,然后调用 main 函数。当该函数调用返回时,程序退出。它不会等待其他(非主)goroutine 完成。
英文:
For a web server (an executable) you need to have a package main
with a func main()
, but it doesn't need to be called main.go - the file name can be anything you want it to be. From the language spec:
> Program execution
>
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论