donglin9068
2015-04-16 14:28 阅读 321
已采纳

Go项目中需要main.go吗?

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    doushi1510 doushi1510 2015-04-16 14:32

    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.

    点赞 评论 复制链接分享
  • dousong3760 dousong3760 2015-04-16 14:37

    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.

    点赞 评论 复制链接分享

相关推荐