Go FAQ
1561 articles — answers that actually help
Ai Sovereignty
6
Async
33
Cargo
8
Cli
65
Collections
21
Compiler Errors
45
Concurrency
129
Core
233
Crates/Toml
1
Database
58
Error Handling
49
File Io
54
Iterators Closures
13
Kubernetes Containers
33
Macros
2
Memory/Borrowing
6
Memory/Ownership
30
Migration Economics
10
Modules
27
Operations Observability
35
Performance
53
Security Hardening
15
Serde
24
Stdlib
172
Strings
49
Structs Enums
26
Testing
52
Tools Testing
39
Type System
81
Unsafe Ffi
20
Web
261
Web Database
45
Go for ML Inference: When It Makes Sense
Go is not ideal for ML inference due to a lack of native tensor libraries and hardware acceleration support, though it can wrap C++ engines.
How to Use TensorFlow or ONNX Runtime from Go
You cannot use TensorFlow directly from Go because it lacks an official Go API, but you can easily use ONNX Runtime via its official Go bindings to execute pre-trained models.
How to Implement Embeddings and Similarity Search in Go
Implement embeddings and similarity search in Go by initializing an embedding model, connecting to a vector database, and using the store's SimilaritySearch method to retrieve relevant documents.
How to Monitor Background Job Health in Go
Monitor background job health in Go by exposing a metrics endpoint that reports job status, error counts, and last execution time via `runtime/metrics` or custom counters. Use a goroutine to track job state and expose it through an HTTP handler for external monitoring tools.
How to Implement Idempotent Job Processing in Go
Prevent duplicate job execution in Go by checking a persistent store for the job ID before running the task logic.
How to Build a Producer-Consumer System in Go
Build a Go producer-consumer system using buffered channels to safely pass data between goroutines.
Vendor dependencies
Run go mod vendor to copy all dependencies from go.mod into a local vendor directory for offline builds.
Private modules
Configure private Go modules by setting the GOPRIVATE environment variable to bypass the public proxy for specific import paths.
Go workspaces
Go workspaces allow managing multiple modules from a single directory using a go.work file for unified builds and tests.
How to Build a CLI Task Manager in Go
Build a basic Go CLI task manager using the flag package to handle add and list commands.
How to Use Homebrew to Distribute Go CLI Tools
Create a custom Homebrew tap with a Ruby formula to build and install your Go CLI tool for distribution.
How to Create a REPL in Go
Create a Go REPL by looping through os.Stdin reads and printing results to os.Stdout.
How Go Slices Work Internally (Slice Header)
A Go slice is a descriptor with a pointer, length, and capacity that references a portion of an underlying array.
How Go Maps Work Internally (Hash Table Implementation)
Go maps use a hash table with buckets and concurrent rehashing for fast, non-blocking lookups and resizing.
How to Filter a Slice in Go
Filter a Go slice using slices.DeleteFunc to remove items in place or slices.Filter to create a new slice with matching elements.
The Loop Variable Capture Gotcha in Go (Pre-1.22)
Fix the Go loop variable capture bug in pre-1.22 versions by assigning the loop variable to a new local variable inside the loop body.
Top 50 Go Mistakes and How to Avoid Them
Use GODEBUG environment variables or source directives to revert specific Go behaviors and avoid breaking changes during upgrades.
Fix: "build constraints exclude all Go files"
Fix the 'build constraints exclude all Go files' error by ensuring at least one file in the package lacks build constraints that exclude your current OS or architecture.
Complete Guide to the sync Package in Go
The sync package provides basic synchronization primitives like Mutex, WaitGroup, and Once for coordinating goroutines in Go.
Patterns for Bounded Concurrency with Context in Go
Limit concurrent goroutines in Go using a buffered channel semaphore and context for cancellation.
How to Use conc Library for Safer Concurrency in Go
The `conc` library provides a lightweight, zero-allocation wrapper around Go's standard concurrency primitives to prevent common race conditions and goroutine leaks without sacrificing performance.
How to Do Code Review for Go Projects
Review Go code by running go vet and gofmt to ensure style compliance and backward compatibility before submission.
How to Write Maintainable Go Code in a Large Team
Write maintainable Go code by minimizing exports, using clear names, and documenting every public identifier with godoc comments.
How to Manage Application Lifecycle in Go (Start, Run, Shutdown)
Use context.Context with signal handlers to propagate cancellation signals for graceful Go application shutdowns.
How to Implement the Unit of Work Pattern in Go
Implement the Unit of Work pattern in Go by creating an interface to track changes and a struct to manage a single database transaction for atomic commits.
How to Implement the Repository Pattern in Go
Implement the Repository Pattern in Go by defining an interface for data operations and creating a struct that implements it to interact with your data source.
How to Use ent for Database Schema and Code Generation
Use `ent` by defining your data model in Go structs and then running the CLI to generate a type-safe, performant codebase that handles schema migrations and query building automatically.
How to Implement Graceful Degradation in Go Services
Implement graceful degradation in Go by wrapping risky calls in defer/recover blocks to catch panics and return safe fallback data.
How to Structure Error Messages in Go (lowercase, no punctuation)
Use lowercase error messages without terminal punctuation to align with Go standard library conventions.
How to Handle Errors Idiomatically in Go
Handle errors in Go by checking return values immediately, using errors.Is for specific types, and wrapping errors with fmt.Errorf to preserve context.
How to Read and Write Binary Files in Go
Read and write raw bytes to files in Go using os.Open, os.Create, and io.ReadFull.
Complete Guide to the path and path/filepath Packages in Go
Use path/filepath for OS-specific file operations and path for URL-style string manipulation.
Complete Guide to the os Package in Go
The Go os package provides a portable interface to operating system functionality like file I/O, environment variables, and process control.
How to Use xiter Patterns for Iterator Utilities
Use the iter.Seq pattern with a yield callback to build memory-efficient, lazy iterators for processing data streams in Go.
How to Use the slices and maps Packages with Iterators
Use slices.Sorted and maps.Keys to iterate over ordered collections and key-value pairs efficiently in Go.
Iterator Patterns: Map, Filter, Take, Skip in Go
Use iter.Map, iter.Filter, iter.Take, and iter.Skip to chain lazy transformations on Go iterators for efficient data processing.
How to Use the Docker SDK in Go
Use the third-party github.com/docker/docker/client package to interact with Docker from Go code.
How to Deploy Go to AWS ECS, GCP Cloud Run, or Azure Container Apps
Deploy Go to AWS ECS, GCP Cloud Run, or Azure Container Apps by building a Docker image, pushing it to a registry, and using platform-specific CLI commands to launch the service.
How to Use Service Mesh (Istio, Linkerd) with Go Services
Integrate Istio or Linkerd with Go services by installing the control plane and enabling sidecar injection to handle traffic management automatically.
Using Struct Value in Map: "cannot assign to struct field in map"
Fix the 'cannot assign to struct field in map' error by retrieving the struct, modifying it, and reassigning it to the map key.
Why You Can't Take the Address of a Map Value in Go
Map lookups in Go return value copies, not references, so you must use pointer types or reassign values to modify map data.
The Append Gotcha: When Append Modifies the Original Slice
Prevent `append` from modifying the original slice by cloning it first to ensure a separate underlying array.
When to Use Pointers vs Values in Go
Use values for small, immutable types and pointers for large structs or when modifying the original data is required.
How Go Manages Memory: Tiny, Small, and Large Allocations
Go optimizes memory by routing tiny, small, and large allocations to specialized paths for efficiency.
How to Use Arenas (arena Package) for Manual Memory Management in Go
Use the Go arena package with the goexperiment.arenas tag to manually allocate and free bulk memory blocks for better performance.
How to Gradually Migrate from Node.js to Go
Migrate from Node.js to Go by rewriting services incrementally and shifting traffic gradually to minimize risk.
How to Rewrite a Python Service in Go: A Step-by-Step Guide
Rewrite a Python service in Go by defining structs, implementing methods, and using goroutines for concurrency.
Go for C# (.NET) Developers: What Changes
Go provides `GODEBUG` settings to control runtime behavior and opt back into legacy behavior when upgrading toolchains. You can set these via the `GODEBUG` environment variable, `godebug` directives in `go.mod`/`go.work`, or `//go:debug` comments in source files.
When to Use Packages vs Interfaces for Modularity in Go
Use interfaces for defining behavior contracts between modules and packages for grouping related implementation code.
Go Code Organization: When to Split Into Multiple Packages
Split Go code into packages when files grow large, logic diverges, or you need to hide internal implementation details.
How to Organize Code in a Go Project
Organize Go projects by creating a module with a go.mod file and separating executables in cmd from libraries in subdirectories.
How to Use the slog Package for Structured Logging
Use the slog package to create structured, machine-readable logs in Go by initializing a handler and calling logger methods with key-value pairs.
How to Monitor Goroutine and Memory Usage in Production
Import net/http/pprof to expose live goroutine and memory metrics via a local HTTP endpoint.
How to Implement Custom Middleware for Observability in Go
Implement Go observability middleware by wrapping your HTTP handler to log request methods, paths, and execution duration.
Algorithmic Complexity (Big O) of Go Built-In Operations (slice, map)
Go's built-in slice and map operations generally offer O(1) performance for basic access and modification, but slice growth and map resizing can trigger O(n) costs due to underlying memory reallocation.
How Devirtualization Works in Go
Go devirtualization optimizes interface calls by replacing indirect dispatch with direct function calls using static analysis or runtime profiling data.
How Inlining Works in the Go Compiler
Inlining replaces function calls with their code bodies to improve performance, controlled by the compiler's heuristics or the -l flag.
Security Best Practices for Go Web Applications
Enable GODEBUG path protections and report vulnerabilities to security@golang.org to secure Go web applications.
How to Use the crypto/tls Package for Custom TLS Configurations
You use the `crypto/tls` package by creating a `tls.Config` struct, customizing fields like `RootCAs` or `InsecureSkipVerify`, and passing it to `tls.Dial` or `http.Transport`.
How to Implement Input Validation and Sanitization in Go
Prevent security vulnerabilities in Go by using html/template for automatic escaping and filepath.IsLocal or os.OpenRoot for safe file access.
How to Handle omitempty with Structs, Pointers, and Zero Values
The omitempty tag skips fields only when they are their zero value, requiring pointers for structs to omit based on specific internal states.
Fix: "json: unsupported type" in Go
Fix the 'json: unsupported type' error by removing functions, channels, or complex interfaces from your struct before marshaling to JSON.
Fix: "json: cannot unmarshal X into Go value of type Y"
Fix the JSON unmarshal error by ensuring your Go struct field names and types exactly match the incoming JSON data structure.
How to Implement a Custom Binary Protocol Parser in Go
Use encoding/binary to read fixed-size fields from an io.Reader into a Go struct for custom binary protocol parsing.
How to Work with Avro in Go
Use the goavro library to define schemas and encode/decode data in Go for efficient binary serialization.
How to Read and Write Parquet Files in Go
The Go standard library does not natively support Parquet files; you must use a third-party library like `github.com/xitongsys/parquet-go`. Install the library, import it, and use `parquet.WriteParquetFile` to write and `parquet.ReadParquetFile` to read data.
How to Sort Strings Locale-Aware in Go with collate
Sort strings in Go using the collate package to respect locale-specific rules like accents and special characters.
How to Normalize Unicode Strings in Go
Normalize Unicode strings in Go using the golang.org/x/text/unicode/norm package with NFC or NFD forms.
How to Work with Character Encodings (UTF-8, ISO-8859-1) in Go
Go uses UTF-8 by default; use the encoding package to convert ISO-8859-1 data to UTF-8 strings.
Why You Shouldn't Compare Structs with == If They Contain Slices
Use reflect.DeepEqual instead of == to compare structs with slices because == only checks memory addresses.
How to Marshal and Unmarshal Nested Structs in Go
Convert nested Go structs to JSON bytes using json.Marshal and parse them back using json.Unmarshal.
How to Create a Type-Safe Enum with Structs in Go
Create a custom type and constants in Go to simulate type-safe enums and enforce valid values at compile time.
How to Detect Goroutine Leaks with goleak in Tests
Use the `goleak` package to automatically detect and report any goroutines that remain running after your test function completes.
How to Write Table-Driven Tests Idiomatically in Go
Write Go table-driven tests by defining a slice of test cases with inputs and expected outputs, then looping over them in a test function to verify behavior.
How to Design for Testability with DI in Go
Use interfaces and constructor injection to swap real dependencies with mocks for isolated, fast Go tests.
How to Debug Go Programs with Delve (dlv)
Debug Go programs by running `dlv debug` to attach the debugger, set breakpoints, and step through code execution.
How to Use staticcheck for Advanced Static Analysis
Install staticcheck via go install and run staticcheck ./... to analyze your Go code for advanced static analysis issues.
How to Use golangci-lint for Comprehensive Linting
Configure and run golangci-lint with a .golangci.yml file to enforce code quality standards like govet and gofumpt across your Go project.
How to Use the go/types Package for Type Checking
The `go/types` package performs static type checking on Go source code by analyzing the Abstract Syntax Tree (AST) to verify type correctness without compiling the program. It is primarily used by tools like IDEs, linters, and refactoring utilities to detect type errors at development time.
The Nil Interface Gotcha in Go (Non-Nil Interface Containing Nil Value)
An interface is non-nil if it holds a type, even if that type's value is nil; check the underlying value with reflection or explicit type assertions.
How Go Implements Interfaces Internally (itab)
Go uses an `itab` structure to map interface methods to concrete type implementations for dynamic dispatch.
How to Call C from Go with Cgo
Call C functions from Go by adding a C preamble comment, importing "C", and using the C. prefix to invoke functions.
How to Call Python from Go (and Vice Versa)
Call Python from Go using os/exec or cgo, and call Go from Python using subprocess or ctypes for shared libraries.
How to Use go:noescape and go:nosplit Directives
Use //go:noescape to optimize pointer handling and //go:nosplit to prevent stack growth interruptions in critical Go functions.
How to Build a Static Site Generator in Go
Build a static site generator in Go by parsing templates and source files to output static HTML pages.
How to Build a Job Scheduler in Go
Build a Go job scheduler using time.NewTicker to run tasks at fixed intervals without external libraries.
How to Build a Metrics Dashboard Backend in Go
Build a Go metrics backend by creating an HTTP server with JSON endpoints using the net/http package.
How to Handle JSON Columns in PostgreSQL from Go
PostgreSQL JSON columns are handled in Go by scanning the column into a `json.RawMessage` or a custom struct using the `pgx` driver. Use `json.RawMessage` to defer parsing or a struct to unmarshal directly into fields.
How to Use ent (Facebook's ORM) for Go Database Access
Define Go schemas, run entc generate, and use the generated client to perform type-safe database operations.
How to Use pgx for Advanced PostgreSQL Features in Go (COPY, LISTEN/NOTIFY)
Use `pgx`'s `CopyFrom` method for high-performance bulk inserts and its `Conn` interface to handle `LISTEN` and `NOTIFY` for real-time event streaming.