First Go Program
In this lesson, you will write, run, and understand your first complete Go program. This is a critical step because it introduces how Go applications are structured and how the Go compiler executes code.
By the end of this lesson, you will clearly understand:
- How a Go program starts execution
- The purpose of
package main - The role of the
main()function - How Go prints output to the console
Minimum Requirements to Run a Go Program
Before writing your first program, ensure:
- Go is installed correctly
- You can run
go versionsuccessfully - You have a terminal or command prompt
Verify Go installation:
go version
Creating Your First Go File
Go source files always use the .go extension.
Create a new file named:
main.go
This filename is commonly used for executable Go programs.
Your First Go Program Code
Below is the simplest complete Go program that prints text to the console:
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
Line-by-Line Explanation
1. package main
Every Go file starts with a package declaration.
package main tells Go that this file belongs to an executable program.
Only packages named main can produce runnable binaries.
2. import "fmt"
The fmt package is part of Go’s standard library.
It provides formatting and printing functions.
Without importing fmt, you cannot print output to the console.
3. func main()
The main() function is the entry point of every Go application.
When you run a Go program:
- The Go runtime looks for
main() - Execution starts from the first line inside it
- The program stops when
main()finishes
4. fmt.Println()
fmt.Println() prints text to the console followed by a new line.
Example output:
Hello, Go!
Running the Go Program
Navigate to the folder containing main.go and run:
go run main.go
Expected output:
- Hello, Go!
How Go Executes This Program
Behind the scenes, Go performs the following steps:
- Reads the source file
- Compiles it into machine code
- Executes the compiled binary
This happens very fast—often in milliseconds—even for large programs.
Compiling Without Running
You can compile the program without running it:
go build main.go
This creates an executable file:
- Windows:
main.exe - macOS/Linux:
main
Run it manually:
./main
Real-World Example
Imagine a server health-check program that prints system status. Every large Go application still begins with:
package mainfunc main()
Even Kubernetes and Docker follow this same foundation.
Common Beginner Mistakes
- Forgetting
package main - Misspelling
main() - Using unused imports (Go will throw errors)
Go enforces clean, correct code from the start.
Practice Exercise
Task
Modify the program to print:
- Your name
- Your age (number)
- Your favorite programming language
Example Output
- Name: Alex
- Age: 25
- Language: Go
What You Will Learn Next
In the next lesson, you will learn how to declare and use variables in Go, including real numeric examples used in production systems.