tommyd456
tommyd456

Reputation: 10673

Is main.go required in a Go project?

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?

Upvotes: 24

Views: 20192

Answers (2)

Leo Correa
Leo Correa

Reputation: 19789

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.

See Program Execution from the Go language specification.

Upvotes: 41

IamNaN
IamNaN

Reputation: 6864

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.

Upvotes: 12

Related Questions