Write Your First Go Program
Let’s write a simple Go program and learn the basics of Go’s structure. By the end of this guide, you’ll understand how to create, run, and build Go programs.Your First Program
Understanding the Code
Let’s break down what each part of the program does:main package is special - it tells Go this is an executable program, not a library.
import statement brings in other packages. Here we’re importing fmt (format), which provides I/O functions like Println.
func main() is the starting point of every Go program. When you run your program, Go automatically calls this function first.
fmt.Println() is a function from the fmt package that prints text to the console followed by a newline.
Functions from other packages are accessed using dot notation:
packageName.FunctionName(). Notice that Println starts with a capital letter - that’s because only capitalized names are exported (visible outside the package).Running vs Building
Go provides two main ways to execute your code:go run - Run Directly
If you have multiple
.go files, you can run them all with: go run .go build - Create an Executable
- On macOS/Linux:
./main - On Windows:
main.exe
Try It Yourself
Now let’s practice with an exercise:Exercise Instructions
- Create a new file or modify your existing
main.go - Print your name using
fmt.Println() - Print your best friend’s name using another
fmt.Println() - First, run it with
go run main.go - Then, build it with
go build main.goand run the executable
Going Further
Let’s enhance our program with comments and Unicode support:Go has excellent Unicode support. You can use any Unicode characters in strings and even in your source code comments!
Common Commands Reference
Here are essential commands you’ll use frequently:| Command | Description |
|---|---|
go run main.go | Compile and run your program |
go run . | Run all .go files in current directory |
go build main.go | Compile into an executable |
go build | Build the current package |
go fmt | Format your code (do this often!) |
go doc fmt Println | View documentation for a function |
Next Steps
Now that you can write and run Go programs, you’re ready to dive deeper into Go fundamentals:Packages & Imports
Learn how to organize code with packages
Variables & Types
Understand Go’s type system and variables
Functions
Master functions and control flow
Exercises
Practice with hands-on exercises