Go's standard library is comprehensive and well-designed. This section provides an overview of the most important packages and their common use cases.
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
Print, Printf, Println: Print to stdoutSprint, Sprintf, Sprintln: Format to stringFprint, Fprintf, Fprintln: Print to writerScan, Scanf, Scanln: Read from stdinstrings - 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
Contains, HasPrefix, HasSuffix: Check substringsSplit, Join: Split and join stringsTrim, TrimSpace, TrimPrefix: Remove charactersReplace, ReplaceAll: Replace substringsToLower, ToUpper: Case conversionstrconv - 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
Getenv, Setenv, Environ: Environment variablesOpen, Create, ReadFile, WriteFile: File operationsExit: Exit programGetwd, Chdir: Working directoryio - Basic I/O Primitives
import "io"
io.Copy(dst, src)
io.ReadAll(reader)
io.WriteString(writer, "hello")
Why io is fundamental
Common interfaces
Reader, Writer: Basic I/O interfacesCloser: Close resourcesSeeker: Random accessio/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
Handler, HandlerFunc: HTTP handlersRequest, Response: HTTP request/responseClient, Server: HTTP client and serverencoding/json - JSON Encoding/Decoding
import "encoding/json"
json.Marshal(data)
json.Unmarshal(jsonData, &result)
Why encoding/json is essential
Common functions
Marshal: Convert Go value to JSONUnmarshal: Convert JSON to Go valueEncoder, Decoder: Stream-based encoding/decodingtime - 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
Now, Date: Get current time or create timeParse, Format: Parse and format timeSleep: Sleep for durationAfter, Tick: Timers and tickerssync - Synchronization Primitives
import "sync"
var mu sync.Mutex
var wg sync.WaitGroup
var once sync.Once
Why sync is crucial
Common types
Mutex, RWMutex: LocksWaitGroup: Wait for goroutinesOnce: Execute onceCond: Condition variablescontext - Context for Cancellation
import "context"
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Why context is essential
Common functions
WithCancel, WithTimeout, WithDeadline: Create contextsBackground, TODO: Base contextsWithValue: Add values to contexterrors - 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.
I/O and Formatting
fmt: Formatting and printingio: I/O primitivesos: Operating system interfacestrings: String manipulationstrconv: String conversionsNetworking
net/http: HTTP client and servernet: Network I/Onet/url: URL parsingData Encoding
encoding/json: JSONencoding/xml: XMLencoding/base64: Base64encoding/hex: HexadecimalConcurrency
sync: Synchronization primitivescontext: Context for cancellationatomic: Atomic operationsTime and Math
time: Time operationsmath: Mathematical functionsmath/rand: Random numbersTesting and Debugging
testing: Testing frameworkruntime: Runtime informationdebug: Debugging supportCollections
slices: Slice utilities (Go 1.21+)maps: Map utilities (Go 1.21+)cmp: Comparison utilities (Go 1.21+)File System
os: File operationspath/filepath: Path manipulationembed: Embed files (Go 1.16+)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.