Skip to main content

How to Write a Go Program with package main and func main

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
package main

func main() {
// the program's first statements
}
PartWhat it does
package mainMarks 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 run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Program​

Create a file named main.go:

main.go, which is in package main, imports fmt and prints Hello from func main inside func main.

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​

Terminal
go run main.go
Output
Hello from func main

A zsh terminal where go run main.go prints Hello from func main.

go run compiled the file and ran main. The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Naming the package something else, such as package hellopackage command-line-arguments is not a main packageUse package main for programs
Leaving out func mainfunction main is undeclared in the main packageAdd func main()
Giving main parameters or a return valuefunc main must have no arguments and no return valuesRead arguments from os.Args, and exit with os.Exit

Troubleshooting​

SymptomLikely causeFix
is not a main packageThe file's package isn't mainChange the first line to package main
go: command not foundGo isn't installed or isn't on the PATHInstall 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​