Standard Library Basics
10 examples to get you started with Standard Library - 7 basic and 3 intermediate.
Search across all documentation pages
10 examples to get you started with Standard Library - 7 basic and 3 intermediate.
mkdir stdlib && cd stdlib && go mod init example.com/stdlib.main.go (or a test file where noted) and run with go run . or go test.go get; import paths like "fmt" resolve from the toolchain.Print values with default formatting.
package main
import "fmt"
func main() {
name, count := "widgets", 3
fmt.Printf("shipped %d %s\n", count, name)
}Printf uses verb tokens (%d, %s, %v) like C-style formatting.Println adds spaces between operands and a trailing newline.fmt.Errorf with %w when wrapping errors in real code.Related: The Go Standard Library: Batteries Included - stdlib philosophy
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", ","))
}strings operates on UTF-8 byte strings; it is not rune-aware for all functions.TrimSpace removes Unicode whitespace, not just ASCII spaces.strings.Builder instead of += in loops.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)
}Atoi is shorthand for ParseInt(s, 10, 0).Parse* functions; invalid input is common at API boundaries.FormatBool, FormatInt, and Itoa cover outbound serialization.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)
}omitempty.json.NewEncoder and json.NewDecoder stream to io.Writer and io.Reader.json.Marshal returns []byte; do not assume a particular key order in comparisons.Related: os, io, bufio & path/filepath - streaming I/O behind JSON
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.ReadFile reads the entire file; use streaming for large inputs.os.IsNotExist(err) to distinguish missing files from permission errors.os.Open when not using ReadFile.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.Copy buffers internally; you rarely need manual byte slices for pipe-style work.io.ReadAll drains a reader into memory; pair with size limits in servers.io.Reader or io.Writer.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)
}
}Scanner defaults to splitting on lines; ScanLines is the default split function.sc.Err() after the loop; Scan returns false on EOF and on errors.sc.Split with a custom function.Related: log, regexp & text/template - text processing packages
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.Since uses a monotonic reading when available, so DST jumps do not distort durations.time.ParseDuration accepts strings like "300ms" and "5m".time.Time, not Unix integers, unless serializing across systems.Related: time, timezones & context Integration - locations and deadlines
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())
}
}cancel() to release timer resources, usually with defer.ctx as the first parameter to functions that may block.context.WithCancel is appropriate when an external event (client disconnect) should stop work.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.HandleFunc registers on http.DefaultServeMux; production code often uses http.NewServeMux.ListenAndServe blocks; configure timeouts on http.Server before production deploys.ResponseWriter and *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).
Reviewed by Chris St. John·Last updated Jul 18, 2026