How to Write a Go Program with package main and func main
Every Go program that you can run has the same two parts: it belongs to package main, and it has a function named main. Go starts the program by calling that function, and the program ends when it returns.
Syntax
package main
func main() {
// the program's first statements
}
| Part | What it does |
|---|---|
package main | Marks the file as part of a program, not a library. |
func main() | The function Go calls to start the program. It takes no arguments and returns nothing. |
The Go specification: "The main package must have package name main and declare a function main that takes no arguments and returns no value." It continues: "Program execution begins by initializing the program and then invoking the function main in package main. When that function invocation returns, the program exits."
The Example
The example prints one line from func main.
Prerequisites
- Go.
go runcompiles and runs a single file. This guide uses Go 1.27.4.
Step 1: Write the Program
Create a file named main.go:

package main
import "fmt"
func main() {
fmt.Println("Hello from func main")
}
import "fmt" brings in the standard formatting package, whose Println prints a line.
Step 2: Run It
go run main.go
Hello from func main

go run compiled the file and ran main. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Naming the package something else, such as package hello | package command-line-arguments is not a main package | Use package main for programs |
Leaving out func main | function main is undeclared in the main package | Add func main() |
Giving main parameters or a return value | func main must have no arguments and no return values | Read arguments from os.Args, and exit with os.Exit |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
is not a main package | The file's package isn't main | Change the first line to package main |
go: command not found | Go isn't installed or isn't on the PATH | Install Go and check with go version |
FAQ
Where are the command-line arguments?
In os.Args, a slice of strings whose first item is the program's own path.
Do I need a go.mod file?
Not for go run main.go with only standard packages. A project that uses other modules needs one, created with go mod init.
Conclusion
A runnable Go program is a file in package main with a func main() that takes nothing and returns nothing. go run main.go compiles it and calls main.
Additional Resources
- Program initialization and execution, in the Go specification.
- Tutorial: Get started with Go.
