Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

Go

Interview questions & answers

Goroutines, interfaces, slices, modules, tooling.

102 questions

  1. Question 1

    What is Go?

    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") }
  2. Question 2

    Goroutines vs OS threads?

    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") }()
  3. Question 3

    What are channels?

    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)
  4. Question 4

    select statement?

    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") }
  5. Question 5

    What is the defer keyword?

    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")
  6. Question 6

    What is a slice?

    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))
  7. Question 7

    Slice growth?

    append may reallocate when exceeding cap; always assign result of append back to the slice variable.

    Example code

    s = append(s, 4)
  8. Question 8

    Arrays vs slices?

    Arrays have fixed size in the type; slices are dynamic views; idiomatic APIs use slices.

    Example code

    var a [2]int
    var b []int
  9. Question 9

    What is a map?

    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"] = 2
  10. Question 10

    Pointers in Go?

    Explicit pointers without pointer arithmetic; pass by value copies structs—use pointers for large structs or mutation.

    Example code

    x := 1
    p := &x
    *p = 2
  11. Question 11

    Interfaces?

    Implicit satisfaction: types implement interfaces by having the methods—small interfaces (io.Reader) are idiomatic.

    Example code

    var r io.Reader = strings.NewReader("hi")
  12. Question 12

    empty interface any?

    interface{} or any holds any dynamic type; requires type assertion or switch to use concretely.

    Example code

    var v any = 1
  13. Question 13

    Error handling?

    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 }
  14. Question 14

    errors.Is and errors.As?

    Unwrap error chains for sentinel comparison or extracting typed errors across layers.

    Example code

    errors.Is(err, os.ErrNotExist)
  15. Question 15

    panic and recover?

    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) } }()
  16. Question 16

    What is a goroutine leak?

    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()
  17. Question 17

    sync.Mutex vs RWMutex?

    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()
  18. Question 18

    sync.WaitGroup?

    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) })
  19. Question 19

    sync.Once?

    Ensures a function runs exactly once—lazy singleton initialization.

    Example code

    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
  20. Question 20

    context.Context?

    Cancellation and deadlines propagate through APIs; always respect ctx.Done() in blocking calls.

    Example code

    // go mod init example.com/m
  21. Question 21

    What is go mod?

    Module system with go.mod (dependencies, minimum Go version) and go.sum checksums for reproducible builds.

    Example code

    // go test ./...
  22. Question 22

    go test?

    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++ {} }
  23. Question 23

    Benchmarks?

    testing.B loop pattern; b.N adjusts iterations; compare with benchstat for micro-optimizations.

    Example code

    // go test -race
  24. Question 24

    What is the race detector?

    Instrumentation finding unsynchronized memory access—slow but run in CI on tests.

    Example code

    // GC runs concurrently; reduce allocs
  25. Question 25

    Garbage collection?

    Concurrent tri-color mark-and-sweep; low STW pauses generally; reduce allocations to improve performance.

    Example code

    // goroutine stacks grow
  26. Question 26

    Stack growth?

    Goroutine stacks start small and grow/shrink—unlike fixed pthread stacks.

    Example code

    type S struct { Embedded }
    // promoted fields
  27. Question 27

    Embedding structs?

    Anonymous field promotes methods and fields—composition over inheritance.

    Example code

    // Exported vs unexported: Name vs name
  28. Question 28

    Exported vs unexported?

    Capitalized identifiers are public across packages; lowercase are package-private.

    Example code

    func init() { fmt.Println("init") }
  29. Question 29

    init functions?

    Multiple per package run in file order before main—use sparingly for registration side effects.

    Example code

    const (
      Zero = iota
      One
    )
  30. Question 30

    What is iota?

    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())
  31. Question 31

    String immutability?

    Strings are read-only byte sequences; conversion to []byte copies; use strings.Builder to build efficiently.

    Example code

    s := "hello"
    fmt.Println([]rune(s))
  32. Question 32

    UTF-8 in strings?

    Strings hold bytes; range iterates runes; len counts bytes not characters.

    Example code

    for _, r := range "hi" { fmt.Println(r) }
  33. Question 33

    What is a rune?

    Alias for int32 representing a Unicode code point.

    Example code

    type T struct{}
    func (T) M() {}
  34. Question 34

    Reflection reflect package?

    Inspect types at runtime—slower and harder to maintain; used in encoding/json and DI.

    Example code

    reflect.TypeOf(1)
  35. Question 35

    Generics (Go 1.18+)?

    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) {}
  36. Question 36

    What is the workspace mode?

    go.work coordinates multiple modules in local development without replace hacks.

    Example code

    // go.work for local modules
  37. Question 37

    CGO?

    Call C from Go—adds build complexity and slower builds; avoid if pure Go suffices.

    Example code

    // import "C" for cgo
  38. Question 38

    Standard library net/http?

    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()
  39. Question 39

    grpc-go?

    gRPC implementation; streams, interceptors, metadata—common microservices transport.

    Example code

    // grpc.NewServer()
  40. Question 40

    What is slog (Go)?

    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)
  41. Question 41

    What is pprof (Go)?

    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)) }()
  42. Question 42

    What is go vet (Go)?

    Static checks for common mistakes; run alongside staticcheck in CI.

    Example code

    // go vet ./...
  43. Question 43

    What is staticcheck (Go)?

    Third-party linter suite beyond vet—catches deprecated APIs and subtle bugs.

    Example code

    // staticcheck ./...
  44. Question 44

    What is golangci (Go)?

    Meta-linter aggregating many tools with config—standard in larger teams.

    Example code

    // golangci-lint run
  45. Question 45

    What is Docker multi-stage (Go)?

    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/base
  46. Question 46

    What is Kubernetes client-go (Go)?

    Watch/informers for controllers; workqueue pattern for reconciliation loops.

    Example code

    // clientset.CoreV1().Pods(ns).Get(ctx, name, metav1.GetOptions{})
  47. Question 47

    What is Wire (Go)?

    Compile-time DI code generation—explicit graphs vs reflection frameworks.

    Example code

    // wire.go //go:generate wire
  48. Question 48

    What is Fx (Go)?

    Runtime DI container popular at Uber—constructor registration and lifecycle hooks.

    Example code

    fx.New(fx.Provide(NewDB), fx.Invoke(Run))
  49. Question 49

    What is Echo / Gin / Chi (Go)?

    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")) })
  50. Question 50

    What is sql.DB pooling (Go)?

    Set MaxOpenConns/MaxIdleConns/ConnMaxLifetime to match DB capacity and avoid stale connections.

    Example code

    db.SetMaxOpenConns(25)
    db.SetConnMaxLifetime(time.Hour)
  51. Question 51

    What is GORM (Go)?

    Popular ORM; beware N+1, hooks overhead—use Preload and explain plans.

    Example code

    db.Where("name = ?", "a").First(&user)
  52. Question 52

    What is Ent (Go)?

    Facebook schema-first entity framework with codegen—type-safe graph queries.

    Example code

    client.User.Query().All(ctx)
  53. Question 53

    What is Protocol Buffers in Go (Go)?

    protoc-gen-go generates types; protojson for HTTP interop.

    Example code

    // protoc --go_out=. api.proto
  54. Question 54

    What is Go workspaces vs replace (Go)?

    go.work for local multi-module dev; replace directive in go.mod for temporary forks.

    Example code

    // go work init ./moda ./modb
  55. Question 55

    What is Semantic import versioning (Go)?

    Major version v2+ in module path suffix /v2—required for incompatible changes.

    Example code

    // require example.com/lib/v2 v2.0.0
  56. Question 56

    What is Error wrapping best practice (Go)?

    Add context at boundaries; compare with errors.Is at decision points.

    Example code

    return fmt.Errorf("load: %w", err)
  57. Question 57

    What is Context values (Go)?

    Pass request-scoped metadata (trace IDs) with caution—avoid stuffing large objects.

    Example code

    ctx := context.WithValue(ctx, key{}, "trace-id")
  58. Question 58

    What is HTTP middleware (Go)?

    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) }) }
  59. Question 59

    What is Graceful shutdown (Go)?

    Listen for signals; context deadline on Server.Shutdown to drain connections.

    Example code

    srv.Shutdown(ctx)
  60. Question 60

    What is Rate limiting golang.org/x/time/rate (Go)?

    Token bucket limiter for APIs—per-IP or per-key.

    Example code

    lim := rate.NewLimiter(rate.Every(time.Second), 10)
    lim.Allow()
  61. Question 61

    What is JWT in Go (Go)?

    jwt-go / lestrrat-go; validate alg, exp, iss; avoid none algorithm bugs.

    Example code

    // jwt.Parse(token, keyFunc)
  62. Question 62

    What is OAuth2 client (Go)?

    golang.org/x/oauth2 Config—handle refresh tokens and context cancellation.

    Example code

    // oauth2.NewClient(ctx, ts)
  63. Question 63

    What is AWS SDK v2 (Go)?

    Context-aware, modular service clients; configure retries and endpoints explicitly.

    Example code

    // cfg, _ := config.LoadDefaultConfig(ctx)
  64. Question 64

    What is S3 uploads (Go)?

    Multipart for large files; checksums; SSE options for compliance.

    Example code

    // s3.PutObject(ctx, &s3.PutObjectInput{...})
  65. Question 65

    What is Kafka sarama / franz-go (Go)?

    Go clients for Kafka; consumer groups, rebalance listeners, exactly-once nuances.

    Example code

    // consumer group Subscribe
  66. Question 66

    What is NATS (Go)?

    Lightweight messaging; JetStream persistence option—simple cloud-native pub/sub.

    Example code

    nc, _ := nats.Connect(nats.DefaultURL)
    nc.Publish("subj", []byte("hi"))
  67. Question 67

    What is Redis (Go)?

    go-redis client; cluster/sentinel modes; context timeouts on every command.

    Example code

    rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
  68. Question 68

    What is MongoDB driver (Go)?

    Official driver; BSON marshaling; transactions in replica sets.

    Example code

    // collection.FindOne(ctx, bson.M{"_id": id}).Decode(&doc)
  69. Question 69

    What is Elasticsearch (Go)?

    Typed clients; bulk indexing; query DSL construction carefully for injection safety.

    Example code

    // esapi.SearchRequest{...}
  70. Question 70

    What is Prometheus client (Go)?

    Counters/gauges/histograms; /metrics endpoint for scraping.

    Example code

    promauto.NewCounter(prometheus.CounterOpts{Name: "hits"}).Inc()
  71. Question 71

    What is OpenTelemetry (Go)?

    Traces and metrics exporters; auto-instrumentation for HTTP/gRPC.

    Example code

    otel.Tracer("app").Start(ctx, "op")
  72. Question 72

    What is Testify assert (Go)?

    Rich assertions and suites; mock package with caution—prefer fakes for domain code.

    Example code

    assert.Equal(t, 1, 1)
  73. Question 73

    What is dockertest (Go)?

    Spin containers in integration tests—slower but realistic DB/queue tests.

    Example code

    // spin postgres container in TestMain
  74. Question 74

    What is Fuzzing native (Go)?

    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) {}) }
  75. Question 75

    What is Build tags (Go)?

    //go:build constraints for OS/arch/feature-specific files—clean optional integrations.

    Example code

    //go:build linux
  76. Question 76

    What is embed package (Go)?

    //go:embed static assets into binary—single deployable artifact.

    Example code

    //go:embed static/*
    var static embed.FS
  77. Question 77

    What is unsafe.Pointer (Go)?

    Escape hatch for syscall/interop; breaks GC guarantees—expert-only.

    Example code

    // unsafe.Pointer(uintptr(unsafe.Pointer(&x)))
  78. Question 78

    What is sync.Map (Go)?

    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)
  79. Question 79

    What is atomic package (Go)?

    Lock-free counters and pointers—faster than mutex for hot stats.

    Example code

    var n atomic.Int64
    n.Add(1)
  80. Question 80

    What is runtime.GOMAXPROCS (Go)?

    Controls parallel OS threads executing Go code—defaults to CPU count; tune in containers with CPU limits.

    Example code

    runtime.GOMAXPROCS(4)
  81. Question 81

    What is schedtrace (Go)?

    GODEBUG schedtrace for scheduler debugging—niche performance tuning.

    Example code

    // GODEBUG=schedtrace=1000
  82. Question 82

    What is escape analysis (Go)?

    Compiler moves values to heap when addresses escape—read -gcflags=-m to optimize allocations.

    Example code

    // go build -gcflags=-m
  83. Question 83

    What is interface nil gotcha (Go)?

    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) // false
  84. Question 84

    What is Method sets (Go)?

    Pointer vs value receivers affect which types satisfy interfaces—T vs *T rules.

    Example code

    // *T has more methods than T for pointer receivers
  85. Question 85

    What is Embedding interfaces (Go)?

    Compose small interfaces into larger ones—idiomatic API design.

    Example code

    type RW interface { io.Reader; io.Writer }
  86. Question 86

    What is HTTP/2 server (Go)?

    Automatic with TLS; configure max concurrent streams and idle timeouts.

    Example code

    // ListenAndServeTLS enables HTTP/2
  87. Question 87

    What is h2c (Go)?

    HTTP/2 cleartext for internal meshes—less common than TLS everywhere.

    Example code

    h2s := &http2.Server{}
    h2s.ServeConn(conn, &http2.ServeConnOpts{...})
  88. Question 88

    What is TLS mutual auth (Go)?

    Client certificates for service-to-service—rotate and validate SANs.

    Example code

    tls.Config{ClientAuth: tls.RequireAndVerifyClientCert}
  89. Question 89

    What is Reverse proxy (Go)?

    httputil.NewSingleHostReverseProxy with proper FlushInterval for streaming.

    Example code

    httputil.NewSingleHostReverseProxy(u)
  90. Question 90

    What is WebSockets (Go)?

    gorilla/websocket or nhooyr; handle ping/pong, read limits, and graceful close.

    Example code

    // upgrader.Upgrade(w, r, nil)
  91. Question 91

    What is SSE in Go (Go)?

    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")
  92. Question 92

    What is Templ / html/template (Go)?

    Auto-escaping against XSS—never use text/template for HTML with user data.

    Example code

    tmpl.Execute(w, data)
  93. Question 93

    What is CSV encoding (Go)?

    encoding/csv handles quotes and commas—set LazyQuotes for messy real-world files.

    Example code

    csv.NewWriter(w).Write([]string{"a", "b"})
  94. Question 94

    What is Time zones (Go)?

    Load location database; store UTC; format with user locale at display edge.

    Example code

    loc, _ := time.LoadLocation("Europe/Paris")
  95. Question 95

    What is Duration parsing (Go)?

    time.ParseDuration for config knobs—clear units vs raw integers.

    Example code

    d, _ := time.ParseDuration("10m")
  96. Question 96

    What is File watching (Go)?

    fsnotify for hot reload tools; debounce events on noisy filesystems.

    Example code

    // fsnotify.NewWatcher()
  97. Question 97

    What is CLI with cobra (Go)?

    Subcommands, flags, completions—standard for Go CLIs.

    Example code

    rootCmd.AddCommand(subCmd)
  98. Question 98

    What is viper (Go)?

    Config merging from files/env/flags—watch out for precedence surprises.

    Example code

    viper.GetString("key")
  99. Question 99

    What is Go plugins (Go)?

    Dynamic loading limited and platform-specific—rarely used in services.

    Example code

    // plugin.Open("p.so")
  100. Question 100

    What is Assembly in Go (Go)?

    Plan9 syntax .s files for hot inner loops—maintainability cost high.

    Example code

    // TEXT ·Add(SB),NOSPLIT,$0
  101. Question 101

    What is wasm/wasi (Go)?

    Compile Go to WebAssembly for browser or WASI runtimes—binary size considerations.

    Example code

    GOOS=js GOARCH=wasm go build -o main.wasm
  102. Question 102

    What is TinyGo (Go)?

    Subset for microcontrollers—smaller binaries, some stdlib gaps.

    Example code

    // tinygo flash -target=nano33