Standard Library Basics
10 examples to get you started with Standard Library - 7 basic and 3 intermediate.
Prerequisites
- Install Go 1.26.x or later from go.dev/dl.
- Create a module:
mkdir stdlib && cd stdlib && go mod init example.com/stdlib. - Save each snippet as
main.go(or a test file where noted) and run withgo run .orgo test. - Stdlib packages need no
go get; import paths like"fmt"resolve from the toolchain.
Basic Examples
1. Formatted output with fmt
Print values with default formatting.
package main
import "fmt"
func main() {
name, count := "widgets", 3
fmt.Printf("shipped %d %s\n", count, name)
}Printfuses verb tokens (%d,%s,%v) like C-style formatting.Printlnadds spaces between operands and a trailing newline.- Prefer
fmt.Errorfwith%wwhen wrapping errors in real code.
Related: The Go Standard Library: Batteries Included - stdlib philosophy
2. String helpers
Transform and inspect strings without manual loops.
package main
import (
"fmt"
"strings"
)
func main() {
s := " hello, Go "
fmt.Println(strings.TrimSpace(s))
fmt.Println(strings.Contains(s, "Go"))
fmt.Println(strings.Split("a,b,c", ","))
}stringsoperates on UTF-8 byte strings; it is not rune-aware for all functions.TrimSpaceremoves Unicode whitespace, not just ASCII spaces.- For heavy building, use
strings.Builderinstead of+=in loops.
3. Parse and format numbers
Convert between strings and numeric types safely.
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("42")
if err != nil {
panic(err)
}
fmt.Println(n * 2)
s := strconv.FormatFloat(3.14, 'f', 2, 64)
fmt.Println(s)
}Atoiis shorthand forParseInt(s, 10, 0).- Always handle errors from
Parse*functions; invalid input is common at API boundaries. FormatBool,FormatInt, andItoacover outbound serialization.
4. JSON encode and decode
Serialize structs to JSON and back.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
u := User{ID: 1, Name: "Ada"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
var decoded User
_ = json.Unmarshal(b, &decoded)
fmt.Println(decoded.Name)
}- Struct tags control JSON field names and
omitempty. json.NewEncoderandjson.NewDecoderstream toio.Writerandio.Reader.json.Marshalreturns[]byte; do not assume a particular key order in comparisons.
Related: os, io, bufio & path/filepath - streaming I/O behind JSON
5. Read a file with os and io
Open a path and read its contents.
package main
import (
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("notes.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data))
}os.ReadFilereads the entire file; use streaming for large inputs.- Check
os.IsNotExist(err)to distinguish missing files from permission errors. - Always close resources opened with
os.Openwhen not usingReadFile.
6. Copy streams with io
Move bytes between readers and writers.
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
func main() {
src := strings.NewReader("hello stream")
var dst bytes.Buffer
n, err := io.Copy(&dst, src)
if err != nil {
panic(err)
}
fmt.Println(n, dst.String())
}io.Copybuffers internally; you rarely need manual byte slices for pipe-style work.io.ReadAlldrains a reader into memory; pair with size limits in servers.- Many stdlib types implement
io.Readerorio.Writer.
7. Line-scan a file with bufio
Read input line by line with minimal memory.
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
s := "line1\nline2\nline3\n"
sc := bufio.NewScanner(strings.NewReader(s))
for sc.Scan() {
fmt.Println(sc.Text())
}
if err := sc.Err(); err != nil {
panic(err)
}
}Scannerdefaults to splitting on lines;ScanLinesis the default split function.- Check
sc.Err()after the loop;Scanreturns false on EOF and on errors. - For token-delimited parsing (CSV fields), use
sc.Splitwith a custom function.
Related: log, regexp & text/template - text processing packages
Intermediate Examples
8. Timers and monotonic clock
Measure elapsed time without wall-clock skew.
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
time.Sleep(50 * time.Millisecond)
fmt.Println(time.Since(start))
}time.Sinceuses a monotonic reading when available, so DST jumps do not distort durations.time.ParseDurationaccepts strings like"300ms"and"5m".- Store instants as
time.Time, not Unix integers, unless serializing across systems.
Related: time, timezones & context Integration - locations and deadlines
9. Context timeout
Cancel work when a deadline expires.
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
select {
case <-time.After(200 * time.Millisecond):
fmt.Println("finished")
case <-ctx.Done():
fmt.Println("canceled:", ctx.Err())
}
}- Always call
cancel()to release timer resources, usually withdefer. - Pass
ctxas the first parameter to functions that may block. context.WithCancelis appropriate when an external event (client disconnect) should stop work.
10. Minimal HTTP server
Serve HTTP with net/http defaults.
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
})
fmt.Println("listening :8080")
http.ListenAndServe(":8080", nil)
}http.HandleFuncregisters onhttp.DefaultServeMux; production code often useshttp.NewServeMux.ListenAndServeblocks; configure timeouts onhttp.Serverbefore production deploys.- Handler functions receive
ResponseWriterand*Request; check method and path inside.
Related: database/sql & net Package Family Overview - net package family | net/http: Go's Batteries-Included HTTP Stack - full HTTP model
Stack versions: This page was written for Go 1.26.x (Green Tea GC default, go fix modernizers - verify patch at build), chi (latest - verify at build), gin (latest - verify at build), echo (latest - verify at build), google.golang.org/grpc (latest - verify at build), sigs.k8s.io/controller-runtime (latest - verify at build), kubebuilder (latest - verify at build), tinygo (latest - verify board targets at build), wazero (latest - verify at build), and golangci-lint (latest - verify linter set at build).