Go code snippets with use cases
28 ready-made code building blocks, sorted by topic.
Basics
- Hello World β A first test of whether Go and the module work.
- Variables and types β Store values and check their type.
- Date and time β Calculate deadlines, format timestamps.
- Enum with iota and Stringer β Print fixed sets of choices (statuses, weekdays, roles) in a type-safe and readable way.
Data structures
- Working with slices β Manage collections of values: add, sort, search.
- Map β Store mappings, e.g. configurations or intermediate results.
- Sort by a custom criterion β Order records, e.g. users by age or name.
- Filter and transform a slice β Select and reshape records β Go's replacement for list comprehensions.
Strings
- Count words β Text analysis, e.g. the most frequent words in a document.
- Regular expression β Find email addresses, phone numbers or patterns in text.
- Manipulate strings β Clean up input, split and assemble text.
Concurrency
- Goroutines with WaitGroup β Complete many independent tasks (downloads, calculations) at the same time.
- Channel with timeout β Wait for a response, but not forever (network, background jobs).
- Counter with mutex β Protect shared data (counters, caches) from concurrent access.
- Cancellation with context β Cleanly end running operations on timeout or user cancellation (HTTP handlers, database).
- Worker pool β Process many tasks with limited parallelism (image processing, API calls).
More snippets
- if / else if / else β React differently depending on the situation, e.g. calculate grades or price tiers.
- for loop and range β Process every element of a list or repeat n times.
- Function with parameters β Bundle recurring logic, e.g. greeting texts or calculations.
- Struct with methods and embedding β Bundle data and behavior, e.g. users, products, game characters.
- Check errors and defer β Guard user input or network access without the program crashing.
- Custom error type with errors.As β Pass on errors with extra information (field, ID, status code) and handle themβ¦
- Read and write a file β Save and load logs, configurations or text data.
- Read and write JSON β Exchange data with web APIs or other programs, save configurations.
- HTTP request (net/http) β Fetch data from a web API.
- Minimal HTTP server β Provide a small web API or a webhook receiver.
- Generic functions Filter and Map β Write reusable helper functions for arbitrary slice types.
- Command-line arguments (flag) β Build your own CLI tools with options.