Why Go?
Go, also known as Golang, is a programming language developed by Google in 2009. It's designed for simplicity, efficiency, and reliability. Here's why you should consider learning Go:
- Simple syntax - Easy to read and write
- Fast compilation - Compiles to machine code
- Built-in concurrency - Goroutines make parallel programming easy
- Memory management - Automatic garbage collection
- Cross-platform - Write once, run anywhere
Installation
macOS
# Using Homebrew
brew install go
# Verify installation
go version
Linux/Ubuntu
# Download and install
wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz
# Add to PATH
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc
Windows
Download from golang.org and run the installer.
Your First Go Program
Create a file called main.go
:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Run it:
go run main.go
Basic Syntax
Variables
// Explicit declaration
var name string = "John"
var age int = 30
// Type inference
name := "John"
age := 30
// Multiple variables
var (
firstName string = "John"
lastName string = "Doe"
age int = 30
)
Constants
const pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)
Data Types
// Basic types
var name string = "Go"
var age int = 10
var price float64 = 99.99
var isActive bool = true
// Arrays
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
// Slices (dynamic arrays)
var fruits []string = []string{"apple", "banana", "orange"}
// Maps
var scores map[string]int = map[string]int{
"Alice": 95,
"Bob": 87,
}
Functions
// Basic function
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
// Function with return value
func add(a, b int) int {
return a + b
}
// Multiple return values
func divide(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// Named return values
func calculate(a, b int) (sum, product int) {
sum = a + b
product = a * b
return // naked return
}
Structs and Methods
// Define a struct
type Person struct {
Name string
Age int
Email string
}
// Method on struct
func (p Person) Greet() {
fmt.Printf("Hi, I'm %s and I'm %d years old\n", p.Name, p.Age)
}
// Pointer receiver method
func (p *Person) SetAge(age int) {
p.Age = age
}
// Usage
person := Person{
Name: "Alice",
Age: 25,
Email: "alice@example.com",
}
person.Greet()
person.SetAge(26)
Control Structures
If-Else
age := 18
if age >= 18 {
fmt.Println("You can vote!")
} else if age >= 16 {
fmt.Println("You can drive!")
} else {
fmt.Println("You're too young!")
}
// Short if statement
if age := 21; age >= 18 {
fmt.Println("You can drink!")
}
Loops
// For loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-like loop
i := 0
for i < 5 {
fmt.Println(i)
i++
}
// Infinite loop
for {
fmt.Println("Infinite loop")
break
}
// Range loop
fruits := []string{"apple", "banana", "orange"}
for index, fruit := range fruits {
fmt.Printf("%d: %s\n", index, fruit)
}
Switch
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of work week")
case "Friday":
fmt.Println("TGIF!")
case "Saturday", "Sunday":
fmt.Println("Weekend!")
default:
fmt.Println("Regular day")
}
Error Handling
Go doesn't have exceptions. Instead, it uses explicit error handling:
func divide(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("cannot divide by zero")
}
return a / b, nil
}
// Usage
result, err := divide(10, 0)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Result: %d\n", result)
Packages and Imports
package main
import (
"fmt"
"math/rand"
"time"
)
// Custom package
import "github.com/user/package"
Next Steps
Now that you understand the basics, you're ready to explore:
- Goroutines - Concurrent programming
- Channels - Communication between goroutines
- Interfaces - Go's way of polymorphism
- Pointers - Memory management
- Testing - Writing tests in Go
Go is a powerful language that's perfect for building scalable applications. Its simplicity makes it easy to learn, while its performance makes it suitable for production systems.
Happy coding with Go! 🚀