Writing Your First Go Program - A Step-by-Step Guide
Writing your first Go program is an exciting step into the world of Go development. This guide will walk you through creating a simple program while explaining fundamental concepts.
Basic Program Structure
Every Go program starts with a package declaration and typically contains imports and a main function. Here's the simplest possible Go program:
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
Let's break down each component:
package main
- Declares this file belongs to the main packageimport "fmt"
- Imports the formatting package for I/O operationsfunc main()
- The program's entry point
Creating Your First Program
- Create a new directory for your project:
mkdir hello
cd hello
- Initialize a new module:
go mod init hello
- Create a new file named
main.go
:
# On Unix-like systems
touch main.go
# On Windows
type nul > main.go
- Open
main.go
in your editor and add this code:
package main
import (
"fmt"
"time"
)
func main() {
name := "Gopher"
currentTime := time.Now()
fmt.Printf("Hello, %s! The time is %s\n",
name,
currentTime.Format("15:04:05"))
// Demonstrate basic arithmetic
x := 10
y := 5
fmt.Println("Let's do some math:")
fmt.Printf("Addition: %d + %d = %d\n", x, y, x+y)
fmt.Printf("Subtraction: %d - %d = %d\n", x, y, x-y)
fmt.Printf("Multiplication: %d * %d = %d\n", x, y, x*y)
fmt.Printf("Division: %d / %d = %d\n", x, y, x/y)
}
Running Your Program
There are several ways to run a Go program:
1. Direct Execution
go run main.go
2. Build and Execute
# Build the executable
go build
# Run the executable
# On Unix-like systems
./hello
# On Windows
hello.exe
3. Build and Install
go install
Understanding the Code
Let's examine the key concepts in our first program:
Package Declaration
package main
- Every Go file must start with a package declaration
package main
indicates this is an executable program- Other packages are used for libraries
Imports
import (
"fmt"
"time"
)
- Import statements bring in external packages
- The
fmt
package provides formatting and I/O functions - The
time
package provides time-related functionality
Variables and Types
name := "Gopher" // String type
x := 10 // Integer type
:=
is the short declaration operator- Go automatically infers the variable type
- Variables must be used to avoid compilation errors
Formatted Output
fmt.Printf("Hello, %s!\n", name)
Printf
allows formatted output using verbs:%s
for strings%d
for integers%f
for floating-point numbers%t
for booleans%v
for any value
Adding More Features
Let's enhance our program with functions and control structures:
package main
import (
"fmt"
"time"
)
// Function to greet a person
func greet(name string) string {
if name == "" {
name = "World"
}
return fmt.Sprintf("Hello, %s!", name)
}
// Function to check if a number is even
func isEven(n int) bool {
return n%2 == 0
}
func main() {
// Demonstrate function calls
message := greet("Gopher")
fmt.Println(message)
// Demonstrate for loop and if statements
fmt.Println("\nChecking numbers from 1 to 5:")
for i := 1; i <= 5; i++ {
if isEven(i) {
fmt.Printf("%d is even\n", i)
} else {
fmt.Printf("%d is odd\n", i)
}
}
// Demonstrate slice (dynamic array)
numbers := []int{1, 2, 3, 4, 5}
fmt.Println("\nNumbers:", numbers)
// Demonstrate map (key-value pairs)
colors := map[string]string{
"red": "#ff0000",
"green": "#00ff00",
"blue": "#0000ff",
}
fmt.Println("\nColors:")
for name, hex := range colors {
fmt.Printf("%s: %s\n", name, hex)
}
}
Common Mistakes and Solutions
1. Unused Imports
// Wrong
import "strings" // Unused import
// Right
import "strings"
str := strings.ToUpper("hello")
2. Unused Variables
// Wrong
x := 10 // Declared but never used
// Right
x := 10
fmt.Println(x)
3. Missing Package Main
// Wrong
package mypackage
func main() {
// ...
}
// Right
package main
func main() {
// ...
}
Building for Different Platforms
Go supports cross-compilation out of the box:
# Build for Windows from Unix
GOOS=windows GOARCH=amd64 go build
# Build for macOS from other platforms
GOOS=darwin GOARCH=amd64 go build
# Build for Linux from other platforms
GOOS=linux GOARCH=amd64 go build
Next Steps
After mastering your first program:
- Learn about Go workspace organization
- Explore Go modules for dependency management
- Discover useful Go tools
- Study Go data types in detail
Additional Resources
- Go Tour - Interactive Go tutorial
- Go by Example - Hands-on examples
- Effective Go - Best practices
- Go Playground - Online Go editor