Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is main.go required in a Go project?

Tags:

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?

like image 409
tommyd456 Avatar asked Apr 16 '15 14:04

tommyd456


People also ask

What is the main Go file in Golang?

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.

What should I keep in my Go program?

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

How do I run a Go program on a new system?

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.

What is the difference between go build and go install?

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.


2 Answers

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.

like image 111
Leo Correa Avatar answered Nov 16 '22 02:11

Leo Correa


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.

like image 25
IamNaN Avatar answered Nov 16 '22 03:11

IamNaN