Pick a topic — languages & databases — 100+ questions and answers in the center column.
Go
Goroutines, interfaces, slices, modules, tooling.
102 questions
Question 1
Statically typed, compiled language from Google; simple syntax, fast builds, strong concurrency with goroutines and channels.
Example code
package main
import "fmt"
func main() { fmt.Println("Go") }Question 2
Goroutines are lightweight user-space tasks multiplexed onto fewer OS threads by the runtime scheduler—cheap to spawn millions in theory.
Example code
go func() { fmt.Println("goroutine") }()Question 3
Typed pipes for sending values between goroutines; unbuffered synchronize; buffered decouple producer/consumer up to capacity.
Example code
ch := make(chan int)
go func() { ch <- 1 }()
fmt.Println(<-ch)Question 4
Waits on multiple channel operations; first ready wins; default makes non-blocking attempts.
Example code
select { case v := <-ch: fmt.Println(v); default: fmt.Println("none") }Question 5
Schedules a function call to run when the surrounding function returns—LIFO order; common for closing files and unlocking mutexes.
Example code
defer fmt.Println("last")
fmt.Println("first")Question 6
Descriptor over an underlying array: pointer, length, capacity; slicing shares storage—copy to avoid accidental aliasing.
Example code
s := []int{1, 2, 3}
fmt.Println(len(s), cap(s))Question 7
append may reallocate when exceeding cap; always assign result of append back to the slice variable.
Example code
s = append(s, 4)Question 8
Arrays have fixed size in the type; slices are dynamic views; idiomatic APIs use slices.
Example code
var a [2]int
var b []intQuestion 9
Hash map built-in; not safe for concurrent writes without sync; zero value is nil map (must make before write).
Example code
m := map[string]int{"a": 1}
m["b"] = 2Question 10
Explicit pointers without pointer arithmetic; pass by value copies structs—use pointers for large structs or mutation.
Example code
x := 1
p := &x
*p = 2Question 11
Implicit satisfaction: types implement interfaces by having the methods—small interfaces (io.Reader) are idiomatic.
Example code
var r io.Reader = strings.NewReader("hi")Question 12
interface{} or any holds any dynamic type; requires type assertion or switch to use concretely.
Example code
var v any = 1Question 13
Explicit error returns, not exceptions; if err != nil pattern; wrap with fmt.Errorf and %w for errors.Is/As.
Example code
if err != nil { return err }Question 14
Unwrap error chains for sentinel comparison or extracting typed errors across layers.
Example code
errors.Is(err, os.ErrNotExist)Question 15
Panic stops the goroutine; recover only useful inside deferred functions—reserve for programming errors, not normal control flow.
Example code
defer func() { if r := recover(); r != nil { fmt.Println(r) } }()Question 16
Blocked goroutines that never complete—e.g. sending on full channel with no receiver; always pair lifecycle.
Example code
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done() }()
wg.Wait()Question 17
Mutex exclusive lock; RWMutex many readers or one writer—tune for read-heavy caches.
Example code
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()Question 18
Wait for a collection of goroutines to finish; Add/Done/Wait must balance carefully.
Example code
var once sync.Once
once.Do(func() { fmt.Println(1) })Question 19
Ensures a function runs exactly once—lazy singleton initialization.
Example code
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()Question 20
Cancellation and deadlines propagate through APIs; always respect ctx.Done() in blocking calls.
Example code
// go mod init example.com/mQuestion 21
Module system with go.mod (dependencies, minimum Go version) and go.sum checksums for reproducible builds.
Example code
// go test ./...Question 22
Built-in testing; table-driven tests idiomatic; -race for data race detector in CI.
Example code
// func BenchmarkX(b *testing.B) { for i := 0; i < b.N; i++ {} }Question 23
testing.B loop pattern; b.N adjusts iterations; compare with benchstat for micro-optimizations.
Example code
// go test -raceQuestion 24
Instrumentation finding unsynchronized memory access—slow but run in CI on tests.
Example code
// GC runs concurrently; reduce allocsQuestion 25
Concurrent tri-color mark-and-sweep; low STW pauses generally; reduce allocations to improve performance.
Example code
// goroutine stacks growQuestion 26
Goroutine stacks start small and grow/shrink—unlike fixed pthread stacks.
Example code
type S struct { Embedded }
// promoted fieldsQuestion 27
Anonymous field promotes methods and fields—composition over inheritance.
Example code
// Exported vs unexported: Name vs nameQuestion 28
Capitalized identifiers are public across packages; lowercase are package-private.
Example code
func init() { fmt.Println("init") }Question 29
Multiple per package run in file order before main—use sparingly for registration side effects.
Example code
const (
Zero = iota
One
)Question 30
Const enumerator resetting per const block; common for bit flags and incrementing enums.
Example code
var b strings.Builder
b.WriteString("hi")
fmt.Println(b.String())Question 31
Strings are read-only byte sequences; conversion to []byte copies; use strings.Builder to build efficiently.
Example code
s := "hello"
fmt.Println([]rune(s))Question 32
Strings hold bytes; range iterates runes; len counts bytes not characters.
Example code
for _, r := range "hi" { fmt.Println(r) }Question 33
Alias for int32 representing a Unicode code point.
Example code
type T struct{}
func (T) M() {}Question 34
Inspect types at runtime—slower and harder to maintain; used in encoding/json and DI.
Example code
reflect.TypeOf(1)Question 35
Type parameters on functions and types; constraints with interfaces; improves map/slice utilities type-safety.
Example code
func N[T comparable](m map[T]int) {}Question 36
go.work coordinates multiple modules in local development without replace hacks.
Example code
// go.work for local modulesQuestion 37
Call C from Go—adds build complexity and slower builds; avoid if pure Go suffices.
Example code
// import "C" for cgoQuestion 38
Production servers with Server timeouts configured; avoid default ListenAndServe without limits in production.
Example code
srv := &http.Server{Addr: ":8080", ReadHeaderTimeout: 5 * time.Second}
// srv.ListenAndServe()Question 39
gRPC implementation; streams, interceptors, metadata—common microservices transport.
Example code
// grpc.NewServer()Question 40
Structured logging in stdlib (Go 1.21+); levels and attributes replace ad-hoc fmt logs in new code.
Example code
slog.Info("msg", "id", 42)Question 41
CPU/heap profiles via net/http/pprof; flame graphs find hot paths and allocations.
Example code
import _ "net/http/pprof"
go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()Question 42
Static checks for common mistakes; run alongside staticcheck in CI.
Example code
// go vet ./...Question 43
Third-party linter suite beyond vet—catches deprecated APIs and subtle bugs.
Example code
// staticcheck ./...Question 44
Meta-linter aggregating many tools with config—standard in larger teams.
Example code
// golangci-lint runQuestion 45
Build binary in golang image, copy to distroless/scratch runtime—small secure images.
Example code
# FROM golang:1.22 AS build
# FROM gcr.io/distroless/baseQuestion 46
Watch/informers for controllers; workqueue pattern for reconciliation loops.
Example code
// clientset.CoreV1().Pods(ns).Get(ctx, name, metav1.GetOptions{})Question 47
Compile-time DI code generation—explicit graphs vs reflection frameworks.
Example code
// wire.go //go:generate wireQuestion 48
Runtime DI container popular at Uber—constructor registration and lifecycle hooks.
Example code
fx.New(fx.Provide(NewDB), fx.Invoke(Run))Question 49
HTTP routers/frameworks; Gin fast reflection binding; Chi stdlib-style routing trees.
Example code
r := chi.NewRouter()
r.Get("/hi", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hi")) })Question 50
Set MaxOpenConns/MaxIdleConns/ConnMaxLifetime to match DB capacity and avoid stale connections.
Example code
db.SetMaxOpenConns(25)
db.SetConnMaxLifetime(time.Hour)Question 51
Popular ORM; beware N+1, hooks overhead—use Preload and explain plans.
Example code
db.Where("name = ?", "a").First(&user)Question 52
Facebook schema-first entity framework with codegen—type-safe graph queries.
Example code
client.User.Query().All(ctx)Question 53
protoc-gen-go generates types; protojson for HTTP interop.
Example code
// protoc --go_out=. api.protoQuestion 54
go.work for local multi-module dev; replace directive in go.mod for temporary forks.
Example code
// go work init ./moda ./modbQuestion 55
Major version v2+ in module path suffix /v2—required for incompatible changes.
Example code
// require example.com/lib/v2 v2.0.0Question 56
Add context at boundaries; compare with errors.Is at decision points.
Example code
return fmt.Errorf("load: %w", err)Question 57
Pass request-scoped metadata (trace IDs) with caution—avoid stuffing large objects.
Example code
ctx := context.WithValue(ctx, key{}, "trace-id")Question 58
Wrap handlers for logging, auth, timeouts—compose as onion around ServeHTTP.
Example code
func mid(next http.Handler) http.Handler { return http.HandlerFunc(func(w,r){ next.ServeHTTP(w,r) }) }Question 59
Listen for signals; context deadline on Server.Shutdown to drain connections.
Example code
srv.Shutdown(ctx)Question 60
Token bucket limiter for APIs—per-IP or per-key.
Example code
lim := rate.NewLimiter(rate.Every(time.Second), 10)
lim.Allow()Question 61
jwt-go / lestrrat-go; validate alg, exp, iss; avoid none algorithm bugs.
Example code
// jwt.Parse(token, keyFunc)Question 62
golang.org/x/oauth2 Config—handle refresh tokens and context cancellation.
Example code
// oauth2.NewClient(ctx, ts)Question 63
Context-aware, modular service clients; configure retries and endpoints explicitly.
Example code
// cfg, _ := config.LoadDefaultConfig(ctx)Question 64
Multipart for large files; checksums; SSE options for compliance.
Example code
// s3.PutObject(ctx, &s3.PutObjectInput{...})Question 65
Go clients for Kafka; consumer groups, rebalance listeners, exactly-once nuances.
Example code
// consumer group SubscribeQuestion 66
Lightweight messaging; JetStream persistence option—simple cloud-native pub/sub.
Example code
nc, _ := nats.Connect(nats.DefaultURL)
nc.Publish("subj", []byte("hi"))Question 67
go-redis client; cluster/sentinel modes; context timeouts on every command.
Example code
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})Question 68
Official driver; BSON marshaling; transactions in replica sets.
Example code
// collection.FindOne(ctx, bson.M{"_id": id}).Decode(&doc)Question 69
Typed clients; bulk indexing; query DSL construction carefully for injection safety.
Example code
// esapi.SearchRequest{...}Question 70
Counters/gauges/histograms; /metrics endpoint for scraping.
Example code
promauto.NewCounter(prometheus.CounterOpts{Name: "hits"}).Inc()Question 71
Traces and metrics exporters; auto-instrumentation for HTTP/gRPC.
Example code
otel.Tracer("app").Start(ctx, "op")Question 72
Rich assertions and suites; mock package with caution—prefer fakes for domain code.
Example code
assert.Equal(t, 1, 1)Question 73
Spin containers in integration tests—slower but realistic DB/queue tests.
Example code
// spin postgres container in TestMainQuestion 74
Go 1.18+ fuzz targets in _test.go files—feeds mutating inputs for security bugs.
Example code
func FuzzParse(f *testing.F) { f.Fuzz(func(t *testing.T, b []byte) {}) }Question 75
//go:build constraints for OS/arch/feature-specific files—clean optional integrations.
Example code
//go:build linuxQuestion 76
//go:embed static assets into binary—single deployable artifact.
Example code
//go:embed static/*
var static embed.FSQuestion 77
Escape hatch for syscall/interop; breaks GC guarantees—expert-only.
Example code
// unsafe.Pointer(uintptr(unsafe.Pointer(&x)))Question 78
Specialized concurrent map for read-heavy caches with stable key sets—not a drop-in for all maps.
Example code
var m sync.Map
m.Store("a", 1)Question 79
Lock-free counters and pointers—faster than mutex for hot stats.
Example code
var n atomic.Int64
n.Add(1)Question 80
Controls parallel OS threads executing Go code—defaults to CPU count; tune in containers with CPU limits.
Example code
runtime.GOMAXPROCS(4)Question 81
GODEBUG schedtrace for scheduler debugging—niche performance tuning.
Example code
// GODEBUG=schedtrace=1000Question 82
Compiler moves values to heap when addresses escape—read -gcflags=-m to optimize allocations.
Example code
// go build -gcflags=-mQuestion 83
Typed nil pointer assigned to interface becomes non-nil interface value—confusing == nil checks.
Example code
var p *T = nil
var i any = p
fmt.Println(i == nil) // falseQuestion 84
Pointer vs value receivers affect which types satisfy interfaces—T vs *T rules.
Example code
// *T has more methods than T for pointer receiversQuestion 85
Compose small interfaces into larger ones—idiomatic API design.
Example code
type RW interface { io.Reader; io.Writer }Question 86
Automatic with TLS; configure max concurrent streams and idle timeouts.
Example code
// ListenAndServeTLS enables HTTP/2Question 87
HTTP/2 cleartext for internal meshes—less common than TLS everywhere.
Example code
h2s := &http2.Server{}
h2s.ServeConn(conn, &http2.ServeConnOpts{...})Question 88
Client certificates for service-to-service—rotate and validate SANs.
Example code
tls.Config{ClientAuth: tls.RequireAndVerifyClientCert}Question 89
httputil.NewSingleHostReverseProxy with proper FlushInterval for streaming.
Example code
httputil.NewSingleHostReverseProxy(u)Question 90
gorilla/websocket or nhooyr; handle ping/pong, read limits, and graceful close.
Example code
// upgrader.Upgrade(w, r, nil)Question 91
Server-sent events over HTTP; simpler than websockets for one-way push.
Example code
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprintf(w, "data: %s\n\n", "hi")Question 92
Auto-escaping against XSS—never use text/template for HTML with user data.
Example code
tmpl.Execute(w, data)Question 93
encoding/csv handles quotes and commas—set LazyQuotes for messy real-world files.
Example code
csv.NewWriter(w).Write([]string{"a", "b"})Question 94
Load location database; store UTC; format with user locale at display edge.
Example code
loc, _ := time.LoadLocation("Europe/Paris")Question 95
time.ParseDuration for config knobs—clear units vs raw integers.
Example code
d, _ := time.ParseDuration("10m")Question 96
fsnotify for hot reload tools; debounce events on noisy filesystems.
Example code
// fsnotify.NewWatcher()Question 97
Subcommands, flags, completions—standard for Go CLIs.
Example code
rootCmd.AddCommand(subCmd)Question 98
Config merging from files/env/flags—watch out for precedence surprises.
Example code
viper.GetString("key")Question 99
Dynamic loading limited and platform-specific—rarely used in services.
Example code
// plugin.Open("p.so")Question 100
Plan9 syntax .s files for hot inner loops—maintainability cost high.
Example code
// TEXT ·Add(SB),NOSPLIT,$0Question 101
Compile Go to WebAssembly for browser or WASI runtimes—binary size considerations.
Example code
GOOS=js GOARCH=wasm go build -o main.wasmQuestion 102
Subset for microcontrollers—smaller binaries, some stdlib gaps.
Example code
// tinygo flash -target=nano33