A.2 Standard Library Overview

Go's standard library is comprehensive and well-designed. This section provides an overview of the most important packages and their common use cases.

Most Important Packages

fmt - Formatting and I/O

import "fmt"

fmt.Printf("Hello, %s\n", "World")
fmt.Println("Hello, World")
fmt.Sprintf("Formatted: %d", 42)

Why fmt is essential

Common functions

strings - String Manipulation

import "strings"

strings.Contains("hello", "ell")        // true
strings.HasPrefix("hello", "he")        // true
strings.Split("a,b,c", ",")             // ["a", "b", "c"]
strings.Join([]string{"a", "b"}, ",")  // "a,b"
strings.TrimSpace("  hello  ")         // "hello"

Why strings is important

Common functions

strconv - String Conversions

import "strconv"

strconv.Atoi("42")              // 42, nil
strconv.Itoa(42)                // "42"
strconv.ParseFloat("3.14", 64)   // 3.14, nil
strconv.FormatFloat(3.14, 'f', 2, 64)  // "3.14"

Why strconv is needed

os - Operating System Interface

import "os"

os.Getenv("PATH")
os.Setenv("KEY", "value")
os.Exit(1)
file, _ := os.Open("file.txt")

Why os is essential

Common functions

io - Basic I/O Primitives

import "io"

io.Copy(dst, src)
io.ReadAll(reader)
io.WriteString(writer, "hello")

Why io is fundamental

Common interfaces

io/ioutil - I/O Utility Functions

import "io/ioutil"

data, _ := ioutil.ReadFile("file.txt")
ioutil.WriteFile("file.txt", data, 0644)
files, _ := ioutil.ReadDir(".")

Note Many ioutil functions are deprecated in favor of os and io packages in Go 1.16+.

net/http - HTTP Client and Server

import "net/http"

http.Get("https://example.com")
http.ListenAndServe(":8080", handler)

Why net/http is powerful

Common types

encoding/json - JSON Encoding/Decoding

import "encoding/json"

json.Marshal(data)
json.Unmarshal(jsonData, &result)

Why encoding/json is essential

Common functions

time - Time and Date

import "time"

time.Now()
time.Sleep(1 * time.Second)
time.Parse("2006-01-02", "2023-01-01")

Why time is important

Common functions

sync - Synchronization Primitives

import "sync"

var mu sync.Mutex
var wg sync.WaitGroup
var once sync.Once

Why sync is crucial

Common types

context - Context for Cancellation

import "context"

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

Why context is essential

Common functions

errors - Error Handling

import "errors"

errors.New("error message")
errors.Is(err, target)
errors.As(err, &target)

Why errors is important

testing - Testing Support

import "testing"

func TestFunction(t *testing.T) { }
func BenchmarkFunction(b *testing.B) { }

Why testing is essential

reflect - Reflection

import "reflect"

reflect.TypeOf(value)
reflect.ValueOf(value)

Why reflect is powerful

Use sparingly Reflection has performance overhead and should be used judiciously.

Quick Reference by Category

I/O and Formatting

Networking

Data Encoding

Concurrency

Time and Math

Testing and Debugging

Collections

File System

Common Use Cases

1. HTTP Server

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

2. JSON API

import (
    "encoding/json"
    "net/http"
)

type Response struct {
    Message string `json:"message"`
}

func handler(w http.ResponseWriter, r *http.Request) {
    resp := Response{Message: "Hello"}
    json.NewEncoder(w).Encode(resp)
}

3. File Operations

import (
    "io/ioutil"
    "os"
)

data, _ := ioutil.ReadFile("file.txt")
os.WriteFile("output.txt", data, 0644)

4. String Processing

import "strings"

text := "  hello,world  "
parts := strings.Split(strings.TrimSpace(text), ",")
result := strings.Join(parts, "-")

5. Time Operations

import "time"

now := time.Now()
duration := 5 * time.Second
future := now.Add(duration)

6. Concurrent Operations

import (
    "sync"
    "time"
)

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(1 * time.Second)
    }()
}
wg.Wait()

The standard library is one of Go's greatest strengths. It provides comprehensive functionality for most common programming tasks, reducing the need for external dependencies.