Go Cheatsheet
Packages
Use this Go reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Package Basics
Every .go file begins with a package declaration. Files in the same directory must share the same package name.
package main // executable (must have func main()) package utils // library package package http // standard convention: package name = directory name
main is the only package name that produces an executable binary.
Import
import "fmt" // single import import ( // grouped import (preferred) "fmt" "os" "strings" )
Import variants
import ( "fmt" m "math" // alias: m.Sqrt(...) . "strings" // dot import: Fields(...) without prefix — avoid in prod _ "image/png" // blank import: side-effects only (init() runs) )
Import paths
// Standard library — by name "fmt" "os" "net/http" // Module path from go.mod "github.com/user/repo/pkg/mypackage" // Internal — only importable by code in the parent tree "mymodule/internal/auth"
Module System (go.mod)
module github.com/user/project go 1.22 require ( github.com/pkg/errors v0.9.1 golang.org/x/sync v0.6.0 )
Key go commands
| Command | Description |
|---|---|
go mod init <module> | initialize a new module |
go mod tidy | add missing / remove unused deps |
go mod download | download all deps to cache |
go get pkg@v1.2.3 | add or upgrade a dependency |
go get pkg@latest | upgrade to latest |
go get pkg@none | remove a dependency |
go list -m all | list all module dependencies |
go mod vendor | copy deps into vendor/ |
go mod verify | verify checksums |
go mod graph | print dependency graph |
Exported vs Unexported Identifiers
Names starting with an uppercase letter are exported (public). Lowercase names are unexported (package-private).
package mypackage var Exported = 42 // visible outside the package var unexported = "secret" // only visible within mypackage type Server struct { Addr string // exported field port int // unexported field } func NewServer(addr string) *Server { ... } // exported constructor func (s *Server) validate() error { ... } // unexported method
Package Naming Conventions
- Short, lowercase, single-word (no underscores or camelCase):
http,io,fmt,bufio. - Package name is typically the last path element:
net/http→ packagehttp. - Avoid stutter:
http.Servernothttp.HTTPServer. _testsuffix in package name for black-box test files:package mypackage_test.
init Functions
init runs automatically after variable initialization. Multiple init functions per file are allowed. Called in the order they appear; packages are initialized in dependency order.
package db var conn *sql.DB func init() { var err error conn, err = sql.Open("postgres", os.Getenv("DSN")) if err != nil { log.Fatal(err) } }
Internal Packages
An internal directory restricts imports to the parent tree only.
mymodule/
cmd/
server/
main.go (can import mymodule/internal/auth)
internal/
auth/
auth.go
pkg/
client/
client.go (CANNOT import mymodule/internal/auth)Commonly Used Standard Library Packages
I/O and Files
import ( "os" "io" "bufio" "path/filepath" ) // os os.Open("file.txt") // *os.File, error os.Create("file.txt") os.ReadFile("file.txt") // []byte, error (Go 1.16+) os.WriteFile("f.txt", data, 0644) os.Remove("file.txt") os.Rename("old", "new") os.MkdirAll("a/b/c", 0755) os.Getenv("HOME") os.Setenv("KEY", "val") os.Environ() // []string os.Args // []string command-line args os.Exit(1) os.Stderr, os.Stdout, os.Stdin // *os.File // io utilities io.ReadAll(r) // read entire reader io.Copy(dst, src) // copy reader to writer io.Discard // /dev/null writer io.LimitReader(r, n) // read at most n bytes io.MultiWriter(w1, w2) // tee writes io.MultiReader(r1, r2) // concatenate readers io.TeeReader(r, w) // read and copy to w simultaneously io.Pipe() // synchronous in-memory pipe // bufio bufio.NewReader(r) bufio.NewWriter(w) bufio.NewScanner(r) scanner.Scan() // read line scanner.Text() // line content // filepath filepath.Join("a", "b", "c") filepath.Dir("/a/b/c.txt") // "/a/b" filepath.Base("/a/b/c.txt") // "c.txt" filepath.Ext("file.txt") // ".txt" filepath.Abs("./rel") filepath.Walk(root, fn) filepath.Glob("*.json")
Strings and Bytes
import ( "strings" "bytes" "unicode" "regexp" "strconv" ) // strings (see Basics page for full list) // bytes — same API as strings but operates on []byte bytes.Contains(b, sub) bytes.Split(b, sep) bytes.TrimSpace(b) var buf bytes.Buffer buf.Write([]byte("hello")) buf.WriteString(" world") buf.Bytes() // unicode unicode.IsLetter(r) unicode.IsDigit(r) unicode.IsSpace(r) unicode.ToUpper(r) // regexp re := regexp.MustCompile(`\d+`) re.FindString("abc123") // "123" re.FindAllString("a1b2c3", -1) // ["1" "2" "3"] re.MatchString("abc123") // true re.ReplaceAllString("a1b2", "X") // "aXbX" re.FindStringSubmatch(`(\w+)@(\w+)`) // groups // strconv strconv.Itoa(42) // "42" strconv.Atoi("42") // 42, nil strconv.FormatFloat(3.14, 'f', 2, 64) // "3.14" strconv.ParseFloat("3.14", 64) strconv.FormatBool(true) // "true" strconv.ParseBool("true") strconv.FormatInt(255, 16) // "ff" strconv.ParseInt("ff", 16, 64)
Networking and HTTP
import ( "net/http" "net/url" "encoding/json" ) // HTTP server http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello") }) http.ListenAndServe(":8080", nil) // Custom mux (Go 1.22+ enhanced routing) mux := http.NewServeMux() mux.HandleFunc("GET /users/{id}", handler) http.ListenAndServe(":8080", mux) // HTTP client resp, err := http.Get("https://example.com") defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) resp, _ = http.Post("https://api.com", "application/json", strings.NewReader(`{}`)) // Custom client with timeout client := &http.Client{Timeout: 10 * time.Second} req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) req.Header.Set("Authorization", "Bearer "+token) resp, _ = client.Do(req) // url u, _ := url.Parse("https://example.com/path?key=val") u.Host, u.Path, u.Query().Get("key") params := url.Values{"q": {"golang"}, "n": {"10"}} params.Encode() // "n=10&q=golang"
Time and Duration
import "time" time.Now() time.Now().UTC() time.Now().Unix() time.Now().UnixMilli() time.Now().Format(time.RFC3339) time.Parse(time.RFC3339, s) time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC) // Durations 5 * time.Second 500 * time.Millisecond time.Hour + 30*time.Minute // Sleep / timer / ticker time.Sleep(1 * time.Second) timer := time.NewTimer(3 * time.Second) <-timer.C // fires once timer.Stop() ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for t := range ticker.C { ... } // Measurement start := time.Now() // ... work ... elapsed := time.Since(start) // Formatting layout: reference time = Mon Jan 2 15:04:05 MST 2006 t.Format("2006-01-02 15:04:05") t.Format("01/02/2006") time.RFC3339, time.RFC1123, time.Kitchen
Encoding
import ( "encoding/json" "encoding/xml" "encoding/csv" "encoding/base64" "encoding/hex" ) // JSON json.Marshal(v) json.MarshalIndent(v, "", " ") json.Unmarshal(data, &v) json.NewEncoder(w).Encode(v) json.NewDecoder(r).Decode(&v) // base64 base64.StdEncoding.EncodeToString(data) base64.StdEncoding.DecodeString(s) base64.URLEncoding.EncodeToString(data) base64.RawURLEncoding.EncodeToString(data) // no padding // hex hex.EncodeToString(data) hex.DecodeString(s)
Crypto and Hashing
import ( "crypto/sha256" "crypto/sha512" "crypto/md5" "crypto/hmac" "crypto/rand" "crypto/tls" "crypto/aes" "crypto/cipher" ) // SHA-256 h := sha256.Sum256([]byte("hello")) // [32]byte hx := fmt.Sprintf("%x", h) // streaming hash sh := sha256.New() sh.Write([]byte("data")) sum := sh.Sum(nil) // []byte // HMAC mac := hmac.New(sha256.New, key) mac.Write(message) sig := mac.Sum(nil) hmac.Equal(sig, expected) // Secure random bytes token := make([]byte, 32) rand.Read(token)
Sync and Concurrency
import ( "sync" "sync/atomic" "context" ) // See Goroutines and Channels pages for full coverage. // context ctx := context.Background() ctx := context.TODO() ctx, cancel := context.WithCancel(parent) ctx, cancel := context.WithTimeout(parent, 5*time.Second) ctx, cancel := context.WithDeadline(parent, deadline) ctx = context.WithValue(parent, key, val) val := ctx.Value(key) ctx.Done() // <-chan struct{} closed on cancellation ctx.Err() // context.Canceled or DeadlineExceeded
Testing
import "testing" // _test.go files; func names start with Test func TestAdd(t *testing.T) { got := Add(2, 3) if got != 5 { t.Errorf("Add(2,3) = %d; want 5", got) } } t.Error("msg") // fail, continue t.Errorf(fmt, args...) t.Fatal("msg") // fail, stop test t.Fatalf(fmt, args...) t.Log("msg") // log (shown on failure) t.Logf(fmt, args...) t.Skip("reason") // skip test t.Run("subtest", func(t *testing.T) { ... }) // subtest // Table-driven tests func TestDivide(t *testing.T) { cases := []struct { a, b float64 expected float64 wantErr bool }{ {10, 2, 5, false}, {0, 0, 0, true}, } for _, tc := range cases { t.Run(fmt.Sprintf("%v/%v", tc.a, tc.b), func(t *testing.T) { got, err := Divide(tc.a, tc.b) if (err != nil) != tc.wantErr { t.Fatalf("unexpected error: %v", err) } if !tc.wantErr && got != tc.expected { t.Errorf("got %v; want %v", got, tc.expected) } }) } } // Benchmarks func BenchmarkAdd(b *testing.B) { for b.Loop() { // Go 1.24+; use i := 0; i < b.N; i++ on older Add(2, 3) } } // go test flags // go test ./... run all tests // go test -v verbose // go test -run TestAdd filter by name (regex) // go test -bench=. -benchmem run benchmarks // go test -race enable race detector // go test -cover -coverprofile=c.out // go tool cover -html=c.out
go Tool Commands
| Command | Description |
|---|---|
go build ./... | compile all packages |
go run main.go | compile and run |
go test ./... | run tests |
go vet ./... | static analysis |
go fmt ./... | format code |
goimports ./... | format + fix imports |
go doc pkg | show package docs |
go doc pkg.Func | show function docs |
godoc -http :6060 | browse docs locally |
go generate ./... | run //go:generate directives |
go install tool@latest | install a binary tool |
go env | print Go environment |
go env GOPATH | print specific env var |
go clean -cache | clean build cache |
go tool pprof | CPU/memory profiling |
go tool trace | trace goroutine events |