Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

🧡 Chapter 24 — Go Programming Language

Complete reference for the Go Standard Library — packages, functions, type signatures, and ready-to-run examples. Go is Google's open-source language built for simplicity, concurrency, and performance.
Part of The Direct Path to Linux Ubuntu — free for all students and developers.

10Packages
240+Symbols
5Examples
go runRun command
Go 1.22Version
FreeNo login
📄 Input / Output 🔤 Strings & Conversion 📐 Math & Time 🌐 Networking 🔒 Concurrency ⚡ Examples

📄 Input / Output

📄 fmtFormatted I/O — print, scan, sprint
🖥️ osOperating system interface — files, env, process
🌊 ioCore I/O interfaces and utilities
📚 bufioBuffered I/O — Scanner, Reader, Writer

🔤 Strings & Conversion

🔤 stringsString manipulation functions
🔢 strconvString ↔ primitive type conversions

📐 Math & Time

📐 mathMathematical constants and functions
🕐 timeTime, duration, timers and sleep

🌐 Networking

🌐 net/httpHTTP client and server

🔒 Concurrency

🔒 syncSynchronization primitives — mutex, waitgroup, once

⚡ Quick Copy-Paste Examples

Save any file as main.go inside a folder, then run with go run main.go or build with go build.

Hello, Go World!

Classic first Go program with a function.

package main

import "fmt"

func greet(name string) string {
    return fmt.Sprintf("Hello, %s! Welcome to Go.", name)
}

func main() {
    fmt.Println(greet("MyWebUniversity"))
    fmt.Println(greet("World"))
}
// go run main.go
// go build -o hello main.go && ./hello

Goroutines & Channels

Concurrent work with goroutines and channel communication.

package main

import (
    "fmt"
    "sync"
)

func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    for j := range jobs {
        result := j * j  // compute square
        fmt.Printf("Worker %d: %d² = %d\n", id, j, result)
        results <- result
    }
}

func main() {
    jobs    := make(chan int, 10)
    results := make(chan int, 10)
    var wg sync.WaitGroup

    // Start 3 workers
    for w := 1; w <= 3; w++ {
        wg.Add(1)
        go worker(w, jobs, results, &wg)
    }

    // Send 9 jobs
    for j := 1; j <= 9; j++ {
        jobs <- j
    }
    close(jobs)

    // Wait then close results
    go func() { wg.Wait(); close(results) }()

    // Collect results
    sum := 0
    for r := range results { sum += r }
    fmt.Println("Sum of squares 1–9:", sum)
}
// go run main.go

Structs, Methods & Interfaces

OOP-style design using Go structs and interfaces.

package main

import (
    "fmt"
    "math"
)

type Shape interface {
    Area()      float64
    Perimeter() float64
    Name()      string
}

type Circle struct{ Radius float64 }
type Rect   struct{ Width, Height float64 }

func (c Circle) Area()      float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }
func (c Circle) Name()      string  { return "Circle" }

func (r Rect) Area()      float64 { return r.Width * r.Height }
func (r Rect) Perimeter() float64 { return 2 * (r.Width + r.Height) }
func (r Rect) Name()      string  { return "Rectangle" }

func printShape(s Shape) {
    fmt.Printf("%-12s area=%-10.3f perimeter=%.3f\n",
        s.Name(), s.Area(), s.Perimeter())
}

func main() {
    shapes := []Shape{
        Circle{Radius: 5},
        Rect{Width: 4, Height: 6},
        Circle{Radius: 2.5},
        Rect{Width: 10, Height: 3},
    }
    for _, s := range shapes {
        printShape(s)
    }
}
// go run main.go

Error Handling & defer

Idiomatic Go error handling with custom error types and defer.

package main

import (
    "errors"
    "fmt"
    "os"
    "strconv"
)

// Custom error type
type ValidationError struct {
    Field   string
    Message string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("validation error: field=%q msg=%s", e.Field, e.Message)
}

func parseAge(s string) (int, error) {
    age, err := strconv.Atoi(s)
    if err != nil {
        return 0, fmt.Errorf("parseAge: %w", err)
    }
    if age < 0 || age > 150 {
        return 0, &ValidationError{Field: "age",
            Message: fmt.Sprintf("%d is out of range [0,150]", age)}
    }
    return age, nil
}

func writeTemp(filename, content string) error {
    f, err := os.Create(filename)
    if err != nil {
        return fmt.Errorf("writeTemp: %w", err)
    }
    defer f.Close()  // runs even if Write fails
    _, err = fmt.Fprintln(f, content)
    return err
}

func main() {
    for _, input := range []string{"25", "abc", "-5", "200"} {
        age, err := parseAge(input)
        if err != nil {
            var ve *ValidationError
            if errors.As(err, &ve) {
                fmt.Printf("Validation: field=%s %s\n", ve.Field, ve.Message)
            } else {
                fmt.Println("Parse error:", err)
            }
            continue
        }
        fmt.Printf("Valid age: %d\n", age)
    }

    if err := writeTemp("test.txt", "defer and cleanup demo"); err != nil {
        fmt.Println("Write error:", err)
    } else {
        fmt.Println("File written successfully")
        defer os.Remove("test.txt")
    }
}
// go run main.go

REST API Client & JSON

Make HTTP requests and parse JSON responses — real-world Go.

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net/http"
    "time"
)

type Post struct {
    UserID int    `json:"userId"`
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
}

func fetchPost(id int) (*Post, error) {
    client := &http.Client{Timeout: 10 * time.Second}
    url := fmt.Sprintf("https://jsonplaceholder.typicode.com/posts/%d", id)

    resp, err := client.Get(url)
    if err != nil {
        return nil, fmt.Errorf("GET %s: %w", url, err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)
    }

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, fmt.Errorf("reading body: %w", err)
    }

    var post Post
    if err := json.Unmarshal(body, &post); err != nil {
        return nil, fmt.Errorf("JSON decode: %w", err)
    }
    return &post, nil
}

func main() {
    for _, id := range []int{1, 2, 3} {
        post, err := fetchPost(id)
        if err != nil {
            log.Printf("Error fetching post %d: %v", id, err)
            continue
        }
        fmt.Printf("Post #%d by User %d\n", post.ID, post.UserID)
        fmt.Printf("  Title: %s\n", post.Title)
        fmt.Printf("  Body : %.60s...\n\n", post.Body)
    }
}
// go run main.go  (requires internet connection)