1.5 Your First Go Program: The package main → func main Flow
TL;DR
- Every runnable Go program starts with
package main. - The code that runs first is inside a special function called
func main(). - The command
go run <filename>.gocompiles and executes your code. - We use built-in "packages" like
fmtto do common things, like printing text.
Why This Matters
Ever wonder how a computer knows where to start running a program? In Go, the answer is always the same: it looks for a special label, package main, and then finds the starting line, func main(). Think of it as the front door to your house. No matter how big your house is, everyone has to come in through the front door.
Learning this simple structure is your first big step. Once you understand this "front door" rule, you can start building any Go application, from a simple command-line tool to a complex web server.
Concepts in Plain English
Here are the few key ideas you need to get started.
- Package: A package is just a way to group Go files together. The special package name
maintells Go, "This is a program that can be run directly."- Analogy: A
packageis like a folder for your code.package mainis the special folder with the "start button" in it.
- Analogy: A
- Function (func): A function is a block of code that does a specific job. The special function name
mainis where your program's execution begins.- Analogy: A
funcis like a recipe for a single dish.func mainis the main course recipe that the chef starts cooking first.
- Analogy: A
- Command: An instruction you give to your computer in the terminal.
go runis the command to tell the Go toolchain to execute your code.- Analogy: A command is like telling your smart speaker to "play music." You're giving a direct order to get something done.
Here’s a quick glossary to keep handy.
| Term | Simple Definition | Where It Shows Up |
package main | The declaration that makes a Go file an executable program. | At the very top of your main.go file. |
func main | The function where your program's execution begins. | Inside your .go file, after the package declaration. |
import "fmt" | A line that brings in Go's built-in "format" package. | Right after package main. |
fmt.Println() | A function from the fmt package that prints a line of text. | Inside func main. |
Quick Setup
For this guide, I'm assuming you've already completed the first couple of steps in this series:
- Go is installed on your computer.
- You have a basic text editor (like VS Code, Sublime Text, or even Notepad).
That's it! No complex project setup is needed.
Do It Step by Step
Let's build and run your very first program from scratch.
1. Create Your Project File
First, we need a place for our code to live.
- Open your terminal (or Command Prompt on Windows).
Create a blank Go file.
# Creates an empty file (on Mac/Linux)
touch main.go
# For Windows, you can use:
# echo. > main.go
Create a new directory (folder) and move into it.
# Create a folder named "hello"
mkdir hello
# Move into the new folder
cd hello
Pro tip — You can name your file anything you want (e.g.,app.go), butmain.gois a common convention for the primary file in a small project.
Your folder should now look like this:
hello/
└── main.go
2. Write the "Hello, World!" Code
Now, open main.go in your text editor and type the following code. We'll go through it line by line.
Tell it what to do. Let's print a message.
package main
import "fmt"
func main() {
// Println is a function from the fmt package that prints a line.
fmt.Println("Hello, Go World!")
}
Make sure you save the file!
Create the main function. This is the code that will run automatically.
package main
import "fmt"
// func main is the special function where program execution begins.
func main() {
}
Import the fmt package. We need this to print text to the screen.
package main
// "fmt" stands for format; it helps us handle input and output.
import "fmt"
Declare it as a runnable program.
// Tells Go this is the main package, the entry point of our app.
package main
3. Run Your Program
Finally, let's run the code. Go back to your terminal, which should still be inside the hello folder.
Check the output. You should see your message printed directly below the command.Input → Output:
$ go run main.go
Hello, Go World!
Run the go run command.
go run main.go
That's it! You just wrote and executed your first Go program. You told the computer exactly where to start (package main, func main) and what to do (fmt.Println).
Here's a breakdown of the terminal commands we used.
| Command | What It Does | Example |
mkdir | Make directory (creates a new folder). | mkdir my-project |
cd | Change directory (moves you into a folder). | cd my-project |
go run | Compiles and runs a Go program. | go run main.go |
Examples
Example A: The Bare Minimum
This is the classic "Hello, World!" you just wrote. It's the simplest possible runnable program in Go. Its only job is to print one line of text and then exit.
// Every executable program must be in 'package main'.
package main
// We import the "fmt" package to get access to functions for printing.
import "fmt"
// This is the function that is automatically called when you run the program.
func main() {
fmt.Println("This is my first Go program.")
}
Example B: A Program That Does Two Things
The main function runs instructions from top to bottom. You can add as many lines as you want. Here, we print two different lines.
package main
import "fmt"
func main() {
// The program runs this line first.
fmt.Println("Step 1: Hello from Go!")
// Then, it runs this line second.
fmt.Println("Step 2: This is the next line.")
}
Running this (go run main.go) would produce:
Step 1: Hello from Go!
Step 2: This is the next line.
This demonstrates the core execution flow. Here is a diagram showing how Go decides what to run.
flowchart LR
subgraph You
A[Write code in main.go] --> B{Run `go run main.go`};
end
subgraph Go
B --> C{Find `package main`?};
C -- Yes --> D{Find `func main`?};
C -- No --> E[Error: Not a main package];
D -- Yes --> F[Execute code inside `main` line by line];
D -- No --> G[Error: main function not found];
F --> H[Program ends];
end
ASCII Fallback: You write code and run go run. Go checks for package main and func main. If both exist, it runs the code inside func main from top to bottom until it's finished. If either is missing, it shows an error.
Common Pitfalls
- Forgetting
package main: If you writepackage myappor forget the line entirely, Go will complain with an error likego run: cannot run non-main package. A runnable program must start withpackage main. - Typo in
func main: Go is case-sensitive.func Main()orfunction main()will not work. It has to befunc main()exactly. If it's wrong, you'll see an error sayingundefined: main.main. - Missing
import "fmt": If you usefmt.Printlnbut forget to import thefmtpackage, Go will stop and tell youundefined: fmt. Always remember to import the tools you need!
FAQ
1. Can I name my file something other than main.go?
Yes, absolutely! You could name it app.go or server.go. As long as it contains package main and func main, go run app.go will work just fine.
2. What exactly is fmt?
fmt is one of Go's standard library packages. Think of it as a pre-built toolbox that Go gives you for free. The fmt toolbox is specialized for handling text—printing it, formatting it, and reading it from users.
3. Why do I have to use the name main?
It's simply the rule of the Go language. By making the names main (for the package) and main (for the function) special, Go creates a clear, unambiguous starting point for every single program. No confusion.
4. Does every .go file need a func main?
No. Only the file that acts as the entry point for your program needs it. Later, you'll write other packages that act as helpers or libraries, and they won't have a func main.
Recap
Great job! You've successfully navigated the most fundamental concept in Go.
- You learned that
package mainis the signpost for a runnable program. - You now know that
func main()is the starting line for the race. - You wrote, saved, and ran your first bit of Go code using
go run. - You saw how code inside
mainruns sequentially, from top to bottom.
From here, you can start putting more interesting "recipes" inside your main function, like working with variables and data.