Lab 09: Packages & Stdlib

Objective

Understand Go modules, package organization, and master the most important standard library packages: fmt, os, strings, strconv, math, time, sort, and log.

Time

30 minutes

Prerequisites

  • Lab 01–08

Tools

  • Docker image: zchencow/innozverse-go:latest


Lab Instructions

Step 1: Go Modules

docker run --rm zchencow/innozverse-go:latest go run - << 'EOF'
package main

import (
    "fmt"
    "runtime"
)

func main() {
    fmt.Println("Go version:", runtime.Version())
    fmt.Println("OS:", runtime.GOOS)
    fmt.Println("Arch:", runtime.GOARCH)
    fmt.Println("CPUs:", runtime.NumCPU())
    fmt.Println("Goroutines:", runtime.NumGoroutine())
}
EOF

💡 Go modules (go.mod) define the module name, Go version, and dependencies. Every Go project should have go.mod. go get package@version adds a dependency. go mod tidy removes unused dependencies. The module cache is in ~/go/pkg/mod — shared across all projects.

📸 Verified Output:


Step 2: os & path/filepath

💡 os.ReadFile and os.WriteFile (Go 1.16+) replace ioutil.ReadFile/WriteFile. They read/write entire files at once. For large files, use os.Open + buffered reading with bufio.Scanner or bufio.Reader to avoid loading everything into memory.

📸 Verified Output:


Step 3: strings & strconv

📸 Verified Output:


Steps 4–8: time, math, sort, log, Capstone scheduler

📸 Verified Output:


Summary

Package
Key functions

os

ReadFile, WriteFile, Getenv, MkdirTemp, Stat

path/filepath

Join, Base, Dir, Ext

strings

TrimSpace, Split, Join, Contains, Builder

strconv

Itoa, Atoi, ParseFloat, FormatInt

time

Now, Parse, Format, Since, Add, Duration

math

Sqrt, Pow, Abs, Round, Floor, Ceil

sort

Ints, Strings, Slice, SearchInts

log

New, Println, Printf, Fatal

Further Reading

Last updated