Go

Go Interview Questions

577 medium-to-hard Golang interview questions with detailed answers, for Go 1.22 to 1.25.

0/577 known
577 questions

Language Fundamentals & Types

Language Fundamentals & TypesQ2Medium

new(T) works for any type. It allocates a zeroed T and returns a *T . make only works for slices, maps and channels. It initializes the runtime data structure behind…

Language Fundamentals & TypesQ3Hard

type Size int64 const ( _ = iota // iota = 0, skipped KB Size = 1 << (10 * iota) // iota = 1 MB // iota = 2: repeats the expression GB // iota = 3 ) const ( A, B = iota,…

Language Fundamentals & TypesQ6Medium

var db *sql.DB func initDB() error { db, err := sql.Open("postgres", dsn) // BUG: declares a new local db if err != nil { return err } return db.Ping() } // Later:…

Language Fundamentals & TypesQ8Hard

i := 0 s := []int{10, 20} i, s[i] = 1, 5 fmt.Println(i, s) a, b := 1, 2 a, b = b, a+b fmt.Println(a, b) Output: 1 [5 20] 2 3 A tuple assignment happens in two phases .…

Language Fundamentals & TypesQ11Medium

s := "héllo" fmt.Println(len(s)) fmt.Println(s[1]) fmt.Println(utf8.RuneCountInString(s)) for i, r := range s { fmt.Printf("%d:%c ", i, r) } Output: 6 195 5 0:h 1:é 3:l…

Language Fundamentals & TypesQ23Hard

Go has goto , but with two rules that keep it safe: It can't jump over a variable declaration if the variable would be in scope at the label. That would create a…

Language Fundamentals & TypesQ33Hard

arr := [3]int{1, 2, 3} for i, v := range arr { if i == 0 { arr[1] = 100 } fmt.Print(v, " ") } fmt.Println() sl := []int{1, 2, 3} for i, v := range sl { if i == 0 { sl[1]…

Arrays, Slices, Maps & Strings

Arrays, Slices, Maps & StringsQ48Hard

arr := [3]int{1, 2, 3} for i, v := range arr { arr[2] = 100 if i == 2 { fmt.Println("array:", v) } } sl := []int{1, 2, 3} for i, v := range sl { sl[2] = 100 if i == 2 {…

Arrays, Slices, Maps & StringsQ65Medium

clear (Go 1.21) has different semantics depending on the type: Map: deletes every entry, so len becomes 0. It is the only way to remove NaN keys, and it is faster than…

Interfaces, Methods & Embedding

Interfaces, Methods & EmbeddingQ83Medium

Use a pointer receiver when any of these apply: The method mutates the receiver. The struct is large, so copying it on every call is expensive. The struct contains…

Interfaces, Methods & EmbeddingQ85Medium

func describe(x any) string { switch v := x.(type) { case nil: return "nil" case int, int64: return fmt.Sprintf("integer %T", v) // v has type any here case error:…

Generics

GenericsQ131Medium

Interviewers want judgment, not enthusiasm. Guidance, broadly following Ian Lance Taylor's "When To Use Generics": When you only call methods: if the function just calls…

Goroutines & the Scheduler

Goroutines & the SchedulerQ148Medium

A goroutine is a function running concurrently and scheduled by the Go runtime in user space. An OS thread is scheduled by the kernel. The main differences: Stack: a…

Goroutines & the SchedulerQ149Medium

The scheduler is built from three parts: G (goroutine): holds the goroutine's stack, saved registers ( gobuf ) and status ( _Grunnable , _Grunning , _Gwaiting ,…

Goroutines & the SchedulerQ151Hard

package main import ( "fmt" "runtime" "sync" ) func main() { runtime.GOMAXPROCS(1) var wg sync.WaitGroup for i := range 5 { wg.Add(1) go func() { defer wg.Done()…

Goroutines & the SchedulerQ153Hard

package main import ( "fmt" "runtime" "time" ) func main() { runtime.GOMAXPROCS(1) go func() { for { } }() time.Sleep(10 * time.Millisecond) fmt.Println("done") } Go…

Goroutines & the SchedulerQ159Hard

sysmon is a runtime thread that runs without a P , so it keeps working even when every P is busy or stuck. It wakes up adaptively, every 20 µs to 10 ms, backing off when…

Goroutines & the SchedulerQ162Medium

A goroutine leak is a goroutine that stays blocked forever, or runs forever, after its work no longer matters. It keeps its stack and everything that stack references,…

Channels & select

Channels & selectQ184Hard

A channel value is a pointer to a runtime.hchan struct allocated on the heap. Its main fields are: qcount , dataqsiz : number of elements currently queued and buffer…

Channels & selectQ191Hard

Go has no built-in priority. The usual pattern is a non-blocking check of the high-priority channel first, followed by a blocking select over everything: for { // 1.…

Channels & selectQ195Medium

package main import "fmt" func main() { ch := make(chan int) go func() { for v := range ch { fmt.Println(v) } }() ch <- 1 ch <- 2 close(ch) } It prints 1 and maybe 2 .…

Channels & selectQ197Medium

chan<- T is send-only and <-chan T is receive-only. A bidirectional chan T converts implicitly to either one, but you can't convert back. The compiler rejects receiving…

Channels & selectQ201Medium

Use select with a default case. If no other case is ready, default runs right away. // Non-blocking send: drop if the consumer is behind (e.g. metrics, logs) select {…

Channels & selectQ202Hard

package main import "fmt" func val(s string, v int) int { fmt.Println("eval", s); return v } func chn(s string, c chan int) chan int { fmt.Println("chan", s); return c }…

Channels & selectQ207Medium

package main import "fmt" func main() { var n chan int u := make(chan int) b := make(chan int, 5) b <- 1 b <- 2 <-b close(b) fmt.Println(len(n), cap(n), len(u), cap(u),…

Channels & selectQ208Medium

The Go proverb says "Don't communicate by sharing memory; share memory by communicating", but the practical rule is: Channels are for passing ownership of data,…

Channels & selectQ214Medium

// Token bucket: burst of 5, refill 10/s func NewLimiter(ctx context.Context, rate time.Duration, burst int) <-chan struct{} { tokens := make(chan struct{}, burst) for…

Concurrency Patterns & sync

Concurrency Patterns & syncQ222Hard

Normal mode: waiters queue in FIFO order, but a woken waiter does not get the lock handed to it. It has to compete with goroutines that are arriving right now, and those…

Concurrency Patterns & syncQ224Medium

type Counter struct { mu sync.Mutex n int } func (c Counter) Inc() { // value receiver c.mu.Lock() defer c.mu.Unlock() c.n++ } func main() { var c Counter var wg…

Concurrency Patterns & syncQ233Hard

var done bool var msg string func setup() { msg = "hello" done = true } func main() { go setup() for !done { } fmt.Println(msg) } No output is guaranteed. This is a data…

Concurrency Patterns & syncQ236Medium

func main() { var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done() fmt.Print(i, " ") }() } wg.Wait() } Go 1.22 and later (when go.mod…

Concurrency Patterns & syncQ241Medium

func fastest(ctx context.Context, mirrors []string) string { ch := make(chan string) for _, m := range mirrors { go func() { ch <- fetch(ctx, m) }() } return <-ch } Only…

Context

ContextQ263Hard

func main() { parent, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() child, cancelChild := context.WithCancel(parent) defer…

ContextQ268Medium

type ctxKey string func main() { ctx := context.WithValue(context.Background(), ctxKey("user"), "alice") ctx = context.WithValue(ctx, ctxKey("user"), "bob") child,…

ContextQ270Medium

The official guidance: use context values only for request-scoped data that crosses process and API boundaries , not for passing optional parameters to functions. Good…

Error Handling & panics

Error Handling & panicsQ302Hard

type MyErr struct{} func (*MyErr) Error() string { return "my err" } func do(fail bool) error { var p *MyErr // nil pointer if fail { p = &MyErr{} } return p // converts…

Error Handling & panicsQ306Hard

func helper() { if r := recover(); r != nil { fmt.Println("recovered:", r) } } func a() { defer helper(); panic("A") } // helper IS the deferred func func b() { defer…

Error Handling & panicsQ308Hard

func main() { defer fmt.Println("1") defer func() { r := recover() fmt.Println("recovered", r) }() defer fmt.Println("3") fmt.Println(f()) panic("boom") } func f() (n…

Error Handling & panicsQ318Medium

func parse(s string) error { var err error if s != "" { n, err := strconv.Atoi(s) // := declares a NEW err in this block if err == nil { fmt.Println("parsed", n) } }…

Memory, GC & Runtime Internals

Memory, GC & Runtime InternalsQ333Hard

Returning or storing its address somewhere that outlives the frame: a global, a heap object, or a channel send of a pointer. Interface conversion , where a non-pointer…

Memory, GC & Runtime InternalsQ337Hard

A write barrier is a small piece of code the compiler inserts around pointer writes into heap memory . It runs only while the GC is marking; otherwise it is skipped by a…

Memory, GC & Runtime InternalsQ342Medium

gc 14 @2.104s 3%: 0.021+4.1+0.034 ms clock, 0.17+1.2/7.9/15+0.27 ms cpu, 48->52->21 MB, 50 MB goal, 0 MB stacks, 0 MB globals, 8 P gc 14 @2.104s 3% : the 14th cycle, 2.1…

Memory, GC & Runtime InternalsQ345Hard

sync.Pool is a concurrency-safe cache of temporary, interchangeable objects. Each P has its own local shard, so Get and Put take no lock in the common case. Objects can…

Memory, GC & Runtime InternalsQ346Medium

In benchmarks, call b.ReportAllocs() or run with -benchmem to get B/op and allocs/op . Since Go 1.24, prefer b.Loop() . It resets the timer automatically and keeps the…

Memory, GC & Runtime InternalsQ348Medium

package main import ( "fmt" "unsafe" ) type A struct { a bool b int64 c bool } type B struct { b int64 a bool c bool } func main() { fmt.Println(unsafe.Sizeof(A{}),…

Memory, GC & Runtime InternalsQ351Hard

The unsafe package documents six valid patterns. Everything else is invalid, even if it happens to work today: Convert *T1 to unsafe.Pointer to *T2 , when T2 is no…

Memory, GC & Runtime InternalsQ357Hard

The GC decides liveness from the point of last use , not from lexical scope. An object can therefore become unreachable, and its finalizer or cleanup can run, in the…

Memory, GC & Runtime InternalsQ363Medium

import _ "net/http/pprof" // registers /debug/pprof/* on DefaultServeMux func main() { go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() // ... }…

Performance, Profiling & Testing

Performance, Profiling & TestingQ376Hard

func square(x int) int { return x * x } func BenchmarkSquare(b *testing.B) { for i := 0; i < b.N; i++ { square(42) } } It typically reports something like 0.25 ns/op —…

Performance, Profiling & TestingQ379Hard

func TestOrder(t *testing.T) { defer fmt.Println("defer") t.Cleanup(func() { fmt.Println("cleanup") }) for i := range 2 { t.Run(fmt.Sprint(i), func(t *testing.T) {…

Performance, Profiling & TestingQ380Medium

Parallel tests in a package run concurrently up to -parallel (default GOMAXPROCS ). Packages themselves run in parallel as separate processes ( -p ). Top-level parallel…

Performance, Profiling & TestingQ393Hard

package main import ( "fmt" "strings" ) func main() { var a strings.Builder a.WriteString("hello") b := a b.WriteString(" world") fmt.Println(b.String()) } It panics :…

Performance, Profiling & TestingQ401Medium

Functions named ExampleXxx in _test.go files serve as both documentation (rendered on pkg.go.dev next to the identifier) and tests. If the function ends with an //…

Modules, Packages & Tooling

Modules, Packages & ToolingQ433Medium

//go:embed (Go 1.16) compiles files into the binary at build time. The directive goes immediately above a package-level variable of type string , []byte , or embed.FS .…

Standard Library, HTTP & Systems Design in Go

Standard Library, HTTP & Systems Design in GoQ450Medium

func h(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) } The…

Standard Library, HTTP & Systems Design in GoQ455Medium

type Resp struct { Items []int `json:"items"` Meta map[string]int `json:"meta"` Ptr *int `json:"ptr"` } var a []int b := []int{} x, _ := json.Marshal(Resp{Items: a}) y,…

Standard Library, HTTP & Systems Design in GoQ460Medium

Scanner: the default max token size is 64 KB ( bufio.MaxScanTokenSize ). A longer line makes Scan() return false, and unless you check sc.Err() (which is…

Standard Library, HTTP & Systems Design in GoQ465Medium

retries := 3 // d := retries * time.Second // compile error: mismatched types int and time.Duration d := time.Duration(retries) * time.Second fmt.Println(d) const n = 3…

Standard Library, HTTP & Systems Design in GoQ469Hard

Classic O(1) LRU: a hash map from key to a node in a doubly linked list ( container/list ); move to front on access, evict from back when over capacity. TTL is checked…

Tricky Output & Code-Review Puzzles

Tricky Output & Code-Review PuzzlesQ478Medium

func main() { var wg sync.WaitGroup var ptrs []*int for i := 0; i < 3; i++ { ptrs = append(ptrs, &i) wg.Add(1) go func() { defer wg.Done() fmt.Print(i, " ") }() }…

Tricky Output & Code-Review PuzzlesQ481Medium

func main() { x := 1 defer fmt.Println("a", x) defer func() { fmt.Println("b", x) }() x = 2 } Output: b 2 a 1 The function value and arguments of a deferred call are…

Tricky Output & Code-Review PuzzlesQ482Hard

func f() (r int) { defer func() { r *= 2 }() return 3 } func g() int { r := 3 defer func() { r *= 2 }() return r } func h() (r int) { defer func() { r *= 2 }() r = 1…

Tricky Output & Code-Review PuzzlesQ483Hard

a := make([]int, 3, 10) b := append(a, 1) c := append(a, 2) fmt.Println(a, b, c) fmt.Println(len(a), len(b), cap(b)) Output: [0 0 0] [0 0 0 2] [0 0 0 2] 3 4 10 a has…

Tricky Output & Code-Review PuzzlesQ484Medium

func modify(s []int) { s[0] = 99 s = append(s, 4) s[1] = 42 } func main() { x := []int{1, 2, 3} // len 3, cap 3 modify(x) fmt.Println(x) // ? y := make([]int, 3, 4) //…

Tricky Output & Code-Review PuzzlesQ486Hard

arr := [3]int{1, 2, 3} for i, v := range arr { if i == 0 { arr[1] = 100 } fmt.Print(v, " ") } fmt.Println(arr) sl := []int{1, 2, 3} for i, v := range sl { if i == 0 {…

Tricky Output & Code-Review PuzzlesQ487Medium

type User struct { Name string Age int } users := []User{{"ann", 30}, {"bob", 40}} for _, u := range users { u.Age++ } fmt.Println(users) // [{ann 30} {bob 40}] u is a…

Tricky Output & Code-Review PuzzlesQ489Medium

type Shape interface{ Area() float64 } type Square struct{ side float64 } func (s *Square) Area() float64 { return s.side * s.side } func main() { var s Shape =…

Tricky Output & Code-Review PuzzlesQ494Medium

func parse(s string) (int, error) { var n int var err error if s != "" { n, err := strconv.Atoi(s) // := declares NEW n and err if err != nil { log.Println("inner:",…

Tricky Output & Code-Review PuzzlesQ495Medium

func worker(id int, wg sync.WaitGroup) { // BUG 2: copied defer wg.Done() fmt.Println("worker", id) } func main() { var wg sync.WaitGroup for i := range 3 { go func() {…

Tricky Output & Code-Review PuzzlesQ497Medium

a := make(chan int, 1) b := make(chan int, 1) a <- 1 b <- 2 select { case v := <-a: fmt.Println("a", v) case v := <-b: fmt.Println("b", v) } ticker := time.NewTicker(10…

Tricky Output & Code-Review PuzzlesQ502Hard

func handle() { if r := recover(); r != nil { fmt.Println("recovered:", r) } } func a() { defer handle(); panic("A") } // 1 func b() { defer func() { handle() }();…

Tricky Output & Code-Review PuzzlesQ503Medium

func main() { defer func() { if r := recover(); r != nil { fmt.Println("recovered", r) } }() var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() var m…

Tricky Output & Code-Review PuzzlesQ505Medium

var x int8 = 127 x++ fmt.Println(x) // ? var u uint8 = 0 u-- fmt.Println(u) // ? m := int8(-128) fmt.Println(-m) // ? fmt.Println(-7/2, -7%2) // ? // const big = 1 << 62…

Tricky Output & Code-Review PuzzlesQ507Medium

s := "héllo" fmt.Println(len(s)) // 6 fmt.Println(s[1]) // 195 fmt.Printf("%c %q\n", s[1], s[1:3]) // Ã "é" for i, r := range s { fmt.Print(i, ":", string(r), " ") //…

Tricky Output & Code-Review PuzzlesQ508Hard

var a, b any = []int{1}, []int{1} fmt.Println(a == b) // panic: runtime error: comparing uncomparable type []int seen := map[any]bool{} seen[[]int{1}] = true // panic:…

Tricky Output & Code-Review PuzzlesQ509Medium

var ErrNotFound = errors.New("not found") e1 := fmt.Errorf("get user: %v", ErrNotFound) e2 := fmt.Errorf("get user: %w", ErrNotFound) fmt.Println(e1) // get user: not…

Tricky Output & Code-Review PuzzlesQ512Hard

s := []int{1, 2, 3, 4, 5} t := append(s[:1], s[3:]...) fmt.Println(t, s) u := []int{1, 2, 3, 4, 5} v := slices.Delete(u, 1, 3) fmt.Println(v, u) Output: [1 4 5] [1 4 5 4…

Classic Concurrency Coding Problems

More Standard Library Essentials

Go Idioms, Design Patterns & Language Design

Observability, Debugging & Production Operations