Go Standard Library Tour
Go ships with a large, high-quality standard library. Many Go programs need no third-party packages at all. This chapter tours the packages you will use most often.
| Package | For |
|---|---|
strings, unicode |
searching, splitting, transforming text |
strconv |
converting between strings and numbers/booleans |
slices, sort, maps |
sorting and searching collections |
time |
dates, times and durations |
encoding/json |
reading and writing JSON |
os, io, bufio |
files, streams, buffered reading |
net/http |
HTTP clients and servers |
math, math/big |
mathematics |
strings
package main
import (
"fmt"
"strings"
)
func main() {
title := " The Go Programming Language "
t := strings.TrimSpace(title)
fmt.Println(strings.ToLower(t))
fmt.Println(strings.Count(t, "g"), strings.HasSuffix(t, "Language"))
fmt.Println(strings.Fields(t))
fmt.Println(strings.EqualFold("GO", "go"), strings.Repeat("-", 5))
before, after, found := strings.Cut("user=admin", "=")
fmt.Println(before, after, found)
var b strings.Builder
for i := 3; i > 0; i-- {
fmt.Fprintf(&b, "%d...", i)
}
b.WriteString("go!")
fmt.Println(b.String())
}the go programming language
4 true
[The Go Programming Language]
true -----
user admin true
3...2...1...go!
strconv
strconv converts with full control and proper error reporting.
package main
import (
"fmt"
"strconv"
)
func main() {
n, _ := strconv.Atoi("250")
f, _ := strconv.ParseFloat("3.75", 64)
b, _ := strconv.ParseBool("true")
hex, _ := strconv.ParseInt("ff", 16, 64)
fmt.Println(n+1, f*2, !b, hex)
fmt.Println(strconv.Itoa(99) + "%")
fmt.Println(strconv.FormatFloat(2.0/3, 'f', 3, 64))
fmt.Println(strconv.Quote("tab\there"))
_, err := strconv.Atoi("12.5")
fmt.Println(err)
}251 7.5 false 255
99%
0.667
"tab\there"
strconv.Atoi: parsing "12.5": invalid syntax
slices, sort and maps
The modern slices package covers most needs; sort.Slice is the older but still common way to sort by a custom rule.
package main
import (
"cmp"
"fmt"
"maps"
"slices"
"sort"
)
type City struct {
Name string
Pop int
}
func main() {
cities := []City{{"Lyon", 520}, {"Nice", 340}, {"Paris", 2100}, {"Lille", 235}}
// sort by population, largest first
slices.SortFunc(cities, func(a, b City) int {
return cmp.Compare(b.Pop, a.Pop)
})
fmt.Println(cities)
// the classic sort package does the same job
sort.Slice(cities, func(i, j int) bool { return cities[i].Name < cities[j].Name })
fmt.Println(cities[0].Name, cities[len(cities)-1].Name)
ages := map[string]int{"zoe": 31, "al": 45, "mo": 28}
keys := slices.Sorted(maps.Keys(ages))
fmt.Println(keys)
nums := []int{5, 1, 4, 1, 5, 9}
slices.Sort(nums)
nums = slices.Compact(nums) // remove consecutive duplicates
slices.Reverse(nums)
fmt.Println(nums)
}[{Paris 2100} {Lyon 520} {Nice 340} {Lille 235}]
Lille Paris
[al mo zoe]
[9 5 4 1]
time
Use time.Date to build a fixed moment, Add and Sub for arithmetic, and Format with Go's reference time — Mon Jan 2 15:04:05 MST 2006 — to choose a layout. You write the reference date the way you want your output to look.
package main
import (
"fmt"
"time"
)
func main() {
start := time.Date(2025, time.March, 14, 9, 30, 0, 0, time.UTC)
fmt.Println(start.Format("2006-01-02 15:04"))
fmt.Println(start.Format("Monday, 2 January 2006"))
fmt.Println(start.Weekday(), start.YearDay())
deadline := start.Add(36 * time.Hour)
fmt.Println(deadline.Format(time.RFC3339))
launch := time.Date(2025, time.December, 25, 0, 0, 0, 0, time.UTC)
wait := launch.Sub(start)
fmt.Println(wait, int(wait.Hours()/24), "days")
d, _ := time.ParseDuration("1h45m")
fmt.Println(d.Minutes(), start.Before(launch))
parsed, err := time.Parse("02/01/2006", "07/11/2024")
fmt.Println(parsed.Format("Jan 2, 2006"), err)
}2025-03-14 09:30
Friday, 14 March 2025
Friday 73
2025-03-15T21:30:00Z
6854h30m0s 285 days
105 true
Nov 7, 2024 <nil>
Note:
time.Now()returns the current time, so its output changes on every run. Examples in this course use fixed dates so the output stays the same.
encoding/json
json.Marshal turns Go values into JSON; json.Unmarshal does the reverse. Struct tags like `json:"name"` control the JSON key names, and only exported fields are encoded.
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
Tags []string `json:"tags,omitempty"`
notes string // unexported: ignored by JSON
}
func main() {
t := Task{ID: 1, Title: "Write docs", notes: "private"}
data, err := json.Marshal(t)
fmt.Println(string(data), err)
pretty, _ := json.MarshalIndent(Task{ID: 2, Title: "Test", Tags: []string{"qa"}}, "", " ")
fmt.Println(string(pretty))
input := `[{"id": 7, "title": "Deploy", "done": true}, {"id": 8, "title": "Relax"}]`
var tasks []Task
if err := json.Unmarshal([]byte(input), &tasks); err != nil {
fmt.Println("bad json:", err)
return
}
for _, task := range tasks {
fmt.Printf("%d %-7s done=%v\n", task.ID, task.Title, task.Done)
}
var bad Task
fmt.Println(json.Unmarshal([]byte(`{"id": "seven"}`), &bad))
}{"id":1,"title":"Write docs","done":false} <nil>
{
"id": 2,
"title": "Test",
"done": false,
"tags": [
"qa"
]
}
7 Deploy done=true
8 Relax done=false
json: cannot unmarshal string into Go struct field Task.id of type int
Other packages worth knowing
The tour above only scratches the surface. A few more packages you will reach for sooner or later:
os— command-line arguments (os.Args), environment variables (os.Getenv), reading and writing whole files (os.ReadFile,os.WriteFile) and exit codes (os.Exit).bufio— buffered reading line by line withbufio.Scanner, the standard way to process large files or terminal input.net/http— a production-ready HTTP server and client.http.HandleFuncplushttp.ListenAndServeis a complete web server in a few lines.log/slog— structured logging with levels and key–value attributes.regexp— regular expressions with guaranteed linear-time matching.flag— parsing command-line flags such as-port=8080.
The documentation for every package is at pkg.go.dev/std, and go doc <package> shows it offline in your terminal. Reading the standard library's source is also a great way to learn idiomatic Go — it is clear, well commented and written by the language's authors.
Test yourself
Which layout string formats a date as 2025-03-14?
YYYY-MM-DD2006-01-02%Y-%m-%dyyyy-mm-dd
Why is an unexported struct field missing from json.Marshal output?
- It is a bug
- The json package can only access exported fields
- It needs
omitempty - Its value was zero
Which function sorts a slice of strings in place?
strings.Sortslices.Sortsort.Stringsonlymaps.Sort