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?
If you read How to Write Go Code carefully, it states that every go program except library is required to include a main.go file, which serves as the backbone of the program. In this case, no matter how you separate the files, keep the main.go.
Keep the main.go If you read How to Write Go Code carefully, it states that every go program except library is required to include a main.go file, which serves as the backbone of the program. In this case, no matter how you separate the files, keep the main.go. 2. Consistent package name
This means that a Go binary does not need system dependencies such as Go tooling to run on a new system, unlike other languages like Ruby, Python, or Node.js. Putting these executables in an executable filepath on your own system will allow you to run the program from anywhere on your system. This is called installing the program onto your system.
To understand what is meant by this, you will use the go install command to install your sample application. The go install command behaves almost identically to go build, but instead of leaving the executable in the current directory, or a directory specified by the -o flag, it places the executable into the $GOPATH/bin directory.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With