Introduction to Go & Setup
What is Go?
Go (Golang) is a modern, statically typed, compiled programming language designed by Google. It is known for its simplicity, performance, and built-in support for concurrency.
Why Go?
- Excellent performance and efficiency
- Built-in concurrency with goroutines
- Simple and clean syntax
- Ideal for cloud-native, microservices, CLI tools, and networking
Installation
Download from go.dev/dl or use package managers.
go version go version go1.22.3 linux/amd64
Your First Go Program
package main import "fmt" func main() { fmt.Println("Hello, Go Mastery!") fmt.Println("Fast, simple, and concurrent!") }
Fast, simple, and concurrent!
Install Go, run go version, then create a new module with
go mod init hello and run your first program with go run main.go.
Variables & Data Types
Declaring Variables
Go offers multiple ways to declare variables. The short declaration := is the most common inside functions.
var name string = "Gopher" age := 10 // Type inferred as int
Zero Values
Variables declared without an initial value are given their zero value (0 for numeric, false for boolean, "" for strings).
Control Flow
The Only Loop: For
Go only has one looping construct: the for loop.
for i := 0; i < 5; i++ { fmt.Println(i) } // while-style loop for n < 100 { n *= 2 }
Functions & Multiple Returns
Multiple Return Values
func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("cannot divide by zero") } return a / b, nil }
Pointers & Structs
Structs
type User struct { ID int Name string } u := User{ID: 1, Name: "Alice"}
Arrays, Slices & Maps
Slices: Dynamic Arrays
s := []int{1, 2, 3}
s = append(s, 4)
Maps: Key-Value Pairs
m := make(map[string]int) m["apples"] = 5
Methods & Interfaces
Interfaces
Go uses implicit interfaces. If a type implements the methods, it implements the interface.
type Shape interface { Area() float64 }
Error Handling
The Idiomatic Way
val, err := doSomething() if err != nil { // Handle error return err }
Concurrency & Goroutines
Goroutines
Use the go keyword to run a function concurrently.
go sayHello()
Channels & Synchronization
Channels
Channels are the pipes that connect concurrent goroutines.
ch := make(chan int) ch <- 42 // Send val := <-ch // Receive
Modules & Testing
Writing Tests
func TestAdd(t *testing.T) { if Add(1, 2) != 3 { t.Errorf("Failed!") } }
Capstone: Concurrent CLI Tool
Build a tool that fetches data from multiple APIs concurrently using goroutines and channels.
// Requirements: // 1. Use net/http to fetch data // 2. Use goroutines for parallel requests // 3. Collect results via channels // 4. Use context for timeouts