Dev Skills
Go tests·191 questions

Mixed final test

Every question from every section. Save this one for just before an interview.

1 / 191

What is the value of city after var city string?

All questions with explanations (answers shown)
  1. 1. What is the value of city after var city string?

    Answer: "" — the empty string

    Every type has a zero value and a string’s is "". Only pointers, slices, maps, channels, funcs and interfaces are nil. Go has no undefined.

  2. 2. Which of these does NOT compile?

    Answer: var b float64 = someInt

    Go never converts between typed numeric values implicitly. You must write float64(someInt). Only untyped constants like 25 adapt to the type they are assigned to.

  3. 3. You import "os" but never use it. What happens?

    Answer: A compile error

    Unused imports and unused local variables are compile errors in Go. Go does this on purpose: it stops dead code from building up.

  4. 4. Which verb prints the type of a value, such as int or string?

    Answer: %T

    %T prints the type: fmt.Printf("%T", 3.5) gives float64. %v prints the value, %s a string, and %q a quoted string. %T is the quickest way to check what type Go inferred for a := variable.

  5. 5. What does fmt.Println(7 / 2) print?

    Answer: 3

    Both operands are integers, so this is integer division and it truncates toward zero. If you want 3.5, convert first: float64(7) / 2.

  6. 6. What is string(65)?

    Answer: "A"

    Converting a number to a string converts a code point to a character. To get the text "65" you need strconv.Itoa(65). go vet flags the common form of this mistake.

  7. 7. Which loop keyword does Go have?

    Answer: Only for

    There is one loop keyword. Drop the init and post clauses and for is a while loop; drop everything and it is infinite.

  8. 8. In a Go switch, when do you need break at the end of a case?

    Answer: Never — cases do not fall through

    Go does not fall through. If you want the C behaviour, the keyword is fallthrough, and you will rarely need it.

  9. 9. What does var i int8 = 127; i++ leave in i?

    Answer: -128

    Integer overflow wraps around with no panic and no warning. Narrowing conversions truncate the same way (int8(x) with x := 200 gives -56), so check the range before converting to a smaller type.

  10. 10. How does Go report that something went wrong?

    Answer: A returned error value you must check

    Errors are ordinary values returned alongside the result. Panic is reserved for broken assumptions, not for expected failures.

  11. 11. What is wrong with data := []int{1,2,3,4,5}; head := data[:2]; head[0] = 99?

    Answer: data[0] is now 99, because the sub-slice shares the backing array

    Slicing does not copy. Both slices point into the same backing array, so a write through one is visible through the other. Use copy when you need independence.

  12. 12. What does len("héllo") return?

    Answer: 6

    len on a string counts bytes, and é is two bytes in UTF-8. For characters you want utf8.RuneCountInString, or range, which decodes for you.

  13. 13. You read v := m["missing"] from a map[string]int. What happens?

    Answer: v is 0, the zero value

    A missing key returns the value type’s zero value and no error. Use the two-value form v, ok := m[k] whenever "absent" and "zero" mean different things.

  14. 14. A function returns error. Inside it you wrote var e *MyError = nil; return e. The caller checks err != nil. What do they see?

    Answer: true — the interface holds a type, so it is not nil

    This is the nil-interface trap. An interface is nil only when both its type and value words are empty. Never return a typed nil as an error; return the literal nil.

  15. 15. How does a type declare that it implements an interface?

    Answer: It does not — having the methods is enough

    Interface satisfaction is implicit. That is why your type can satisfy an interface written years later in a package that has never heard of it.

  16. 16. When is a pointer receiver required rather than optional?

    Answer: When the method mutates the receiver, or the type holds a mutex

    A value receiver gets a copy, so mutation is lost. And copying a struct containing a sync.Mutex copies the lock, which is a bug go vet catches.

  17. 17. What does %w do in fmt.Errorf("get user %d: %w", id, err)?

    Answer: Wraps it so errors.Is and errors.As can still see the original

    %w preserves the error chain. %v flattens it to text and breaks errors.Is, which is sometimes what you want: it hides an internal error from callers.

  18. 18. Inside a loop over filenames you write f, _ := os.Open(name); defer f.Close(). What is the problem?

    Answer: Every file stays open until the whole function returns

    defer fires when the function returns, not the block. Over a large directory you hit the open-file limit (ulimit -n, often 1024). Move the body into its own small function.

  19. 19. A struct field is named email (lowercase). What does json.Marshal do with it?

    Answer: Omits it entirely

    Only exported fields are marshalled. A lowercase field is missing from your API response with no error, and the bug looks like the frontend’s fault.

  20. 20. Why is out += x inside a loop over 100,000 strings slow?

    Answer: Strings are immutable, so each += allocates and copies the whole string

    Immutability makes it O(n²). strings.Builder (or strings.Join) writes into one growing buffer instead.

  21. 21. What is the idiomatic Go test structure?

    Answer: A table of cases, looped over with t.Run for named subtests

    Table-driven tests make the twelfth case one line, and t.Run lets you run just one with go test -run "TestX/case_name".

  22. 22. What does this print? a := make([]int, 3, 10); b := append(a, 1); c := append(a, 2); fmt.Println(b[3], c[3])

    Answer: 2 2

    a has spare capacity, so both appends write into the same backing array at index 3, and the second overwrites the first. b and c share that slot. Never append to one slice from two places.

  23. 23. s := []int{1,2,3,4,5}; t := s[1:3:3]; t = append(t, 99). What is s afterwards?

    Answer: [1 2 3 4 5]

    The full slice expression s[1:3:3] sets the capacity of t to 3-1 = 2, so append has no room and copies to a new array. s is untouched. Without the third index, append would have overwritten s[3] with 99.

  24. 24. What does this print? x := 1; defer fmt.Println(x); x = 2

    Answer: 1

    A deferred call’s arguments are evaluated when the `defer` statement runs, not when the call fires. x was 1 then. To see the later value, defer a closure: defer func() { fmt.Println(x) }().

  25. 25. m := map[string]int{"a":1,"b":2,"c":3}. What does for k := range m { fmt.Print(k) } print?

    Answer: Any order, and it can differ between runs

    Map iteration order is unspecified, and the runtime deliberately randomises it so nobody depends on it. For a stable order, collect the keys and sort them: slices.Sorted(maps.Keys(m)).

  26. 26. var p *bytes.Buffer; var w io.Writer = p; fmt.Println(w == nil). What prints?

    Answer: false

    w holds a type (*bytes.Buffer) and a nil pointer value. An interface is nil only when it has no type at all, so w == nil is false. This is the same trap as returning a typed nil error.

  27. 27. What makes an identifier visible outside its package?

    Answer: Starting it with a capital letter

    Capitalisation is the access modifier. Println is exported; println would be package-private. There is no public or private keyword.

  28. 28. What does for i := 0; i < 3; i++ { defer fmt.Print(i) } print when the function returns?

    Answer: 210

    Deferred calls run last-in, first-out, and the argument i is evaluated when the defer line runs, not when the call fires. So the values 0, 1, 2 are saved and printed in reverse.

  29. 29. m := map[string]int{} then v, ok := m["x"]. What are v and ok?

    Answer: 0 false

    Reading a missing key never panics. You get the zero value of the value type, and the comma-ok form tells you the key was not there.

  30. 30. a := []int{1, 2, 3}, b := a[:2], b = append(b, 9). What is a now?

    Answer: [1 2 9]

    b shares a’s backing array and still has spare capacity (3), so append writes 9 into the slot a[2] already uses instead of allocating a new array.

  31. 31. What is len("héllo")?

    Answer: 6

    len on a string counts bytes, not characters. é takes two bytes in UTF-8, so five characters make six bytes. Use utf8.RuneCountInString to count runes.

  32. 32. func inc(n int) { n++ }, then x := 1; inc(x); fmt.Println(x). What prints?

    Answer: 1

    Go passes arguments by value, so inc changes its own copy. To change x, take a *int and write *n++, calling it as inc(&x).

  33. 33. type P struct{ X, Y int }. What does P{1, 2} == P{1, 2} give?

    Answer: true

    Structs whose fields are all comparable can be compared with ==, field by field. Two values with the same fields are equal; addresses do not matter.

  34. 34. n, err := strconv.Atoi("12a"). What do you get?

    Answer: n is 0 and err is non-nil

    Errors are returned values, not exceptions. On failure the number comes back as its zero value and err explains what went wrong, so you check err before using n.

  35. 35. const ( A = iota * 10; B; C ). What is C?

    Answer: 20

    Each line in the block repeats the last expression with iota going up by one. C is on line 2, so it is 2 * 10.

  36. 36. Where must recover() be called for it to stop a panic?

    Answer: Directly inside a deferred function

    Only deferred calls still run while a panic unwinds the stack, so recover only does something there. Called in normal code it just returns nil.

  37. 37. switch x := 2; x { case 1: fmt.Print("a"); case 2: fmt.Print("b"); case 3: fmt.Print("c") }. What prints?

    Answer: b

    Go cases do not fall through. Only the matching case runs, unless you write fallthrough on purpose.

  38. 38. var p *MyErr = nil, then var err error = p. What is err == nil?

    Answer: false

    An interface is nil only when both its type and its value are empty. err holds the type *MyErr with a nil value, so it is not nil. Return a plain nil from functions instead of a typed nil pointer.

  39. 39. type Counter struct{ n int } with func (c Counter) Inc() { c.n++ }. After var c Counter; c.Inc(), what is c.n?

    Answer: 0

    A value receiver gets a copy, so Inc bumps the copy and throws it away. Use a pointer receiver (c *Counter) when a method must change the value.

  40. 40. var v any = 3.0, then a type switch with case int, case float64 and default. Which case runs?

    Answer: float64

    An untyped float constant like 3.0 becomes float64 when stored in an interface. A type switch matches the dynamic type exactly, with no conversion.

  41. 41. err := fmt.Errorf("load: %w", ErrNotFound). What is errors.Is(err, ErrNotFound)?

    Answer: true

    %w wraps the error and keeps it in the chain. errors.Is walks that chain, so it finds ErrNotFound even though == would fail.

  42. 42. Which name can code in a different package use?

    Answer: UserName

    Go has no public keyword. A name is exported only when it starts with an uppercase letter.

  43. 43. type U struct{ Name string; age int }. What does json.Marshal(U{"Ann", 30}) produce?

    Answer: {"Name":"Ann"}

    encoding/json can only see exported fields, so age is skipped without any error. Without a tag the key is the field name exactly as written.

  44. 44. Which test will go test find and run?

    Answer: func TestAdd(t *testing.T) in add_test.go

    A test lives in a file ending _test.go, its name starts with Test followed by a non-lowercase letter, and it takes exactly one *testing.T.

  45. 45. In what order does for k := range m visit a map’s keys?

    Answer: Unspecified, and it can change from run to run

    Map order is not defined and Go randomises it on purpose so nobody relies on it. Sort the keys yourself when the order matters.

  46. 46. type S struct{}, func (s *S) M() {}, type I interface{ M() }. What happens with var _ I = S{}?

    Answer: Compile error: S does not implement I because M has a pointer receiver

    Only *S has the method M, so a plain S value does not satisfy I. Writing &S{} fixes it.

  47. 47. var b byte = 255; b++. What is b?

    Answer: 0

    byte is uint8. Integer overflow at run time wraps around silently, so 255 + 1 becomes 0.

  48. 48. Two sum with a map[int]int from value to index. What is the time and space?

    Answer: O(n) time, O(n) space

    One pass, with an O(1) average map lookup per element, and the map can hold up to n entries.

  49. 49. a := []int{1, 2, 3, 4}; b := a[1:3]; slices.Reverse(b); fmt.Println(a) prints:

    Answer: [1 3 2 4]

    b shares a's backing array, so reversing b swaps the middle two elements of a. Use slices.Clone when you need an independent copy.

  50. 50. You need the top 10 words out of 5 million distinct words. Which is the better follow-up to sorting everything?

    Answer: A min-heap of size 10 with container/heap: O(n log k)

    Keep only k items. Each push and pop costs O(log k), so the total is O(n log k) instead of O(n log n). Remember to call heap.Push(h, x), not h.Push(x).

  51. 51. Inside for i, r := range s over a string, what are i and r?

    Answer: i is the byte offset, r is a rune

    Ranging over a string decodes UTF-8. i jumps by the size of each character in bytes. s[i] would give a byte, not a rune.

  52. 52. i := sort.SearchInts(s, x) and x is bigger than every element. What must you do before reading s[i]?

    Answer: Check i < len(s), because it returns len(s)

    sort.Search and its helpers return n when the condition is never true. Reading s[n] panics.

  53. 53. In an LRU cache built with container/list and a map, why does each list entry store its key?

    Answer: Because eviction starts from the list node, and you need the key to delete it from the map

    You evict from the back of the list. Without the key you cannot remove the map entry, and the map keeps the evicted node alive.

  54. 54. A backtracking function does out = append(out, cur) and every saved subset ends up the same. Why?

    Answer: All saved slices share cur's backing array, so later changes overwrite them; save slices.Clone(cur)

    A slice is a header pointing at an array. Saving it saves the pointer, not the values. Copy at the moment you save the answer.

  55. 55. dp := make([][]int, n) and then dp[0][0] = 1. What happens?

    Answer: It panics: each row is a nil slice until you make it

    make([][]int, n) makes n nil rows. Loop and make each row before you index into it.

  56. 56. Roughly what does a new goroutine cost?

    Answer: ~2KB of stack that grows on demand

    About 2KB, growing as needed. That is why running a hundred thousand goroutines is routine, and a hundred thousand OS threads is not.

  57. 57. What happens when you send on a closed channel?

    Answer: It panics

    Sending on a closed channel panics. Receiving from one is fine: once any buffered values are drained, you get the zero value and ok == false immediately.

  58. 58. Who should close a channel?

    Answer: The sender, and only one goroutine

    Closing means "no more values are coming", which only the sender knows. Two goroutines closing the same channel panics.

  59. 59. What does receiving from a nil channel do?

    Answer: Blocks forever

    It blocks forever, and that is useful. Setting a channel variable to nil inside a select disables that case, which is the standard way to drop a branch out of a loop.

  60. 60. Where must wg.Add(1) go?

    Answer: Before the go statement

    Inside the goroutine it races with Wait, which can see a count of zero and return before anything started.

  61. 61. go func() { ch <- expensive() }() where nobody ever receives. What have you built?

    Answer: A goroutine leak — it blocks on the send forever

    A blocked goroutine is never collected, and neither is anything it references. Fix it with a buffer of 1, or by selecting on ctx.Done().

  62. 62. Two goroutines read and write the same map with no synchronisation. What does the runtime do?

    Answer: Detects it and hard-crashes with "concurrent map writes"

    Maps are not safe for concurrent use, and the runtime crashes on purpose rather than let the map corrupt (a read racing a write reports "concurrent map read and map write"). The check is best-effort, so still run -race.

  63. 63. Where should a context.Context live?

    Answer: The first parameter of the function, named ctx

    A context belongs to one call, not to an object. Storing it in a struct means one long-lived context outlives the request it came from.

  64. 64. What is context.Value for?

    Answer: Request-scoped data crossing API boundaries — request id, user id, trace span

    If a function needs it to do its job, it is a parameter. Context values are invisible to the compiler — nothing tells you one is missing until it fails at runtime.

  65. 65. Which command finds data races?

    Answer: go test -race ./...

    The race detector adds checks to the binary and reports races that actually occur at runtime, so exercise the concurrent paths in your tests. Run it in CI.

  66. 66. When should you prefer a mutex over a channel?

    Answer: When you are guarding shared state rather than transferring ownership

    A mutex around a cache is simpler and faster than a goroutine owning a map behind a channel. Channels transfer ownership; mutexes protect fields.

  67. 67. What does a select with a default case do when no channel is ready?

    Answer: Runs default immediately

    A default makes the select non-blocking. Without one it waits until some case is ready, choosing at random among those that are.

  68. 68. ch := make(chan int, 1); ch <- 7; close(ch). What do two receives v, ok := <-ch give?

    Answer: 7 true, then 0 false

    Closing does not discard buffered values. You drain 7 with ok == true, then every later receive returns the zero value with ok == false immediately. That is how for v := range ch knows to stop.

  69. 69. In a select loop, one case receives from in, which is nil. What happens to that case?

    Answer: It is never chosen; the other cases still work

    Sending to or receiving from a nil channel blocks forever, so in a select that case simply never fires. Setting a drained channel to nil is the standard way to switch off one case while the others keep running. Only a select whose cases are *all* nil, with no default, blocks forever.

  70. 70. main runs go fmt.Println("hi") and then returns straight away. What happens?

    Answer: Most likely nothing prints, because the program exits when main returns

    The program ends as soon as main returns and does not wait for other goroutines. Use a sync.WaitGroup or a channel to wait.

  71. 71. ch := make(chan int), then ch <- 1 in main with no other goroutines. What happens?

    Answer: fatal error: all goroutines are asleep - deadlock!

    A send on an unbuffered channel waits for a receiver. No goroutine can ever receive, so the runtime notices and stops the program.

  72. 72. ch := make(chan int, 1); ch <- 7; close(ch); a := <-ch; b, ok := <-ch. What are a, b and ok?

    Answer: 7 0 false

    Closing does not throw away buffered values, so a gets 7. After that the channel is empty and closed, so receives give the zero value and ok is false.

  73. 73. Which command reports data races while your tests run?

    Answer: go test -race

    The race detector is built in when you pass -race. It only sees races that actually happen during the run, so tests need to exercise the concurrent paths.

  74. 74. After ctx, cancel := context.WithCancel(parent) and cancel(), what does ctx.Err() return?

    Answer: context.Canceled

    Once a context is done, Err says why. A manual cancel gives context.Canceled; a passed deadline or timeout gives context.DeadlineExceeded.

  75. 75. Why call wg.Add(1) before the go statement instead of inside the new goroutine?

    Answer: Wait could run before the goroutine calls Add, see a zero counter and return early

    Wait returns when the counter is zero. If the goroutine has not started yet, the counter may still be zero. Adding first removes that race.

  76. 76. ch is an empty channel. What does select { case v := <-ch: fmt.Print(v); default: fmt.Print("none") } do?

    Answer: Prints none right away

    A select with a default never blocks. If no case is ready at that moment, default runs.

  77. 77. Several goroutines write to the same plain map with no lock. What can happen?

    Answer: The program can crash with fatal error: concurrent map writes

    Built-in maps are not safe for concurrent writes, and the runtime crashes the program when it catches it. Guard the map with a sync.Mutex, or use sync.Map for the cases it fits.

  78. 78. What does mu.Lock(); defer mu.Unlock() at the top of a function give you?

    Answer: The lock is released when the function returns, including early returns and panics

    Deferred calls run when the surrounding function returns, however it returns. That is why the unlock sits right next to the lock.

  79. 79. On Go 1.22 or later, for i := 0; i < 3; i++ { wg.Add(1); go func() { defer wg.Done(); fmt.Print(i) }() } followed by wg.Wait(). What prints?

    Answer: Each of 0, 1 and 2 once, in any order

    Since Go 1.22 every loop iteration gets its own i, so each goroutine sees a different value. The scheduler decides who runs first, so the order is not fixed.

  80. 80. What does ~int mean in a constraint?

    Answer: Any type whose underlying type is int, so type UserID int qualifies

    Without the tilde, only int itself satisfies it — your own named types would not.

  81. 81. When is an interface the right tool instead of a generic?

    Answer: When the operation is about what a type does, not what it is

    Generics parameterise over types; interfaces abstract over behaviour. Shape is an interface. Sum[T Number] is a generic.

  82. 82. Which package should you use for random values in a security token?

    Answer: crypto/rand

    math/rand is not cryptographically secure: its output can be predicted from earlier outputs, or reproduced outright if it was seeded with something guessable like the time. For tokens that is a real vulnerability, not a nitpick.

  83. 83. When should you reach for generics?

    Answer: After you have written the concrete version two or three times

    Premature generics make code harder to read and often guess the wrong abstraction. Check slices and maps first: much of what people hand-roll is already there.

  84. 84. Which of these compiles?

    Answer: func Max[T cmp.Ordered](a, b T) T { if a > b { return a }; return b }

    > needs an ordered type. any allows every type, and comparable only guarantees == and !=, so both are rejected. cmp.Ordered is the constraint for < and >. (For two values, the built-in max already exists.)

  85. 85. type Celsius float64. Which constraint lets Sum[T] accept a []Celsius?

    Answer: interface{ ~float64 }

    ~float64 means "any type whose underlying type is float64", which includes Celsius. Plain float64 matches only float64 itself. any would accept Celsius but would not allow + in the body.

  86. 86. What does for i := range 3 { fmt.Print(i) } print in Go 1.22+?

    Answer: 012

    Since Go 1.22 you can range over an integer n, which yields 0 up to n-1. It is the short form of for i := 0; i < 3; i++.

  87. 87. What did Go 1.22 add that removed most of the reason to use a web framework?

    Answer: Method and path-parameter routing: mux.HandleFunc("GET /users/{id}", h)

    Before 1.22 ServeMux matched paths only, so you routed methods by hand. Now r.PathValue("id") gets the parameter and the framework buys you very little.

  88. 88. What is the correct order inside a handler?

    Answer: Set headers, then WriteHeader, then write the body

    Headers set after WriteHeader are silently dropped, and writing a body implies WriteHeader(200). Always return right after writing an error, or you get "superfluous WriteHeader".

  89. 89. What is wrong with http.ListenAndServe(":8080", mux) in production?

    Answer: The zero-value server has no timeouts, so one slow client can hold a connection forever

    Configure http.Server with ReadHeaderTimeout (the Slowloris defence), ReadTimeout, WriteTimeout and IdleTimeout.

  90. 90. What is a middleware in Go?

    Answer: A function taking an http.Handler and returning an http.Handler

    That is the whole mechanism. You compose by nesting, so no framework is required.

  91. 91. Your recover middleware wraps every handler. A goroutine you started inside a handler panics. What happens?

    Answer: It kills the whole process — a parent recover cannot catch it

    Recover only works in the panicking goroutine’s own deferred function. Every long-lived goroutine you launch needs its own defer recover().

  92. 92. Why must signal.Notify’s channel be buffered?

    Answer: signal.Notify never blocks, so an unbuffered channel with nobody receiving yet drops the signal

    make(chan os.Signal, 1). Get this wrong and your graceful shutdown silently never triggers.

  93. 93. A handler calls w.Write(body) and then w.WriteHeader(http.StatusCreated). What does the client get?

    Answer: 200 OK, and the server logs "superfluous response.WriteHeader call"

    The first Write sends a 200 if no status was set. After that the status is fixed, so the later WriteHeader only produces a log line. Call WriteHeader(201) before writing the body.

  94. 94. You start srv := &http.Server{Addr: ":8080", Handler: mux} with no timeouts. Which one fix matters most?

    Answer: Set ReadHeaderTimeout, so a client that sends headers very slowly cannot hold a connection open forever

    With no timeouts, a slow client (Slowloris) can keep many connections open by trickling headers. ReadHeaderTimeout closes them. Set ReadTimeout, WriteTimeout and IdleTimeout too.

  95. 95. What is *sql.DB?

    Answer: A connection pool, safe for concurrent use

    Create one for the whole program, share it across goroutines, and never close it per request.

  96. 96. What is the default value of SetMaxOpenConns if you never call it?

    Answer: Unlimited

    Unlimited, so a traffic spike keeps opening connections until Postgres hits max_connections and refuses new ones. The pool limit is your backpressure. Always set it.

  97. 97. Which is safe against SQL injection?

    Answer: db.QueryRowContext(ctx, "SELECT ... WHERE id = $1", id)

    Placeholders send the query and the data separately, so the data can never be parsed as SQL. There is no exception to this, not even for "internal" endpoints.

  98. 98. After looping with rows.Next(), what must you not forget?

    Answer: defer rows.Close() and checking rows.Err()

    Without Close you leak a pooled connection, and iteration errors surface only through rows.Err(): the loop just ends early and looks successful.

  99. 99. You call repo.GetUser once per row inside a loop over 200 notes. What is this called?

    Answer: The N+1 problem

    201 round trips instead of one. Fix it with a JOIN, or one batched query using WHERE id = ANY($1). It is one of the most common performance bugs in web code, in any language.

  100. 100. Why use a named return value in a function that runs a transaction?

    Answer: So the deferred rollback can see whether an error occurred

    This is one of the few places where naming a return pays off: defer func() { if err != nil { tx.Rollback() } }().

  101. 101. Which of these should never happen inside a transaction?

    Answer: An HTTP call to a third-party service

    A transaction holds a pooled connection for its whole life. A slow third party then ties up a database connection, and enough of those use up the whole pool.

  102. 102. Why should you never write SELECT *?

    Answer: Adding a column breaks every Scan at once, with an unhelpful error

    Scan matches columns positionally. List the columns and a new one changes nothing.

  103. 103. Find the bug: rows, err := db.QueryContext(ctx, q); if err != nil { return err }; for rows.Next() { if err := rows.Scan(&x); err != nil { return err } }; return rows.Err()

    Answer: There is no defer rows.Close(), so an early return inside the loop leaks a pooled connection

    rows holds a connection until it is closed. When Next returns false the rows close themselves, but any early return skips that. Put defer rows.Close() right after the error check.

  104. 104. A list query sometimes returns fewer rows than expected, with no error. The loop is for rows.Next() { ... } and then return items, nil. What is the most likely cause?

    Answer: rows.Err() is never checked, so an error part-way through (such as a dropped connection) looks like the end of the results

    Next returns false both at the end and on an error. Only rows.Err() tells them apart. Return it after the loop.

  105. 105. Which is the right fix for db.QueryContext(ctx, fmt.Sprintf("SELECT id FROM users WHERE email = '%s'", email))?

    Answer: Pass the value as a parameter: db.QueryContext(ctx, "SELECT id FROM users WHERE email = $1", email)

    Building SQL with Sprintf is SQL injection. With a placeholder the value is sent separately from the SQL text, so it can never change the query. Escaping by hand always misses a case.

  106. 106. A handler runs a slow report with db.QueryContext(context.Background(), q). The user closes the tab. What happens, and what is the fix?

    Answer: The query keeps running and holding a connection; pass r.Context() so it is cancelled when the client goes away

    context.Background() is never cancelled. r.Context() is cancelled when the client disconnects, and the driver then cancels the query and frees the connection.

  107. 107. A handler calls w.Write([]byte("ok")) and then w.Header().Set("Content-Type", "text/plain"). What does the client get?

    Answer: The body, but without that header: headers are sent with the first write

    The first Write sends the status line and headers. Anything you set on the header map afterwards is ignored. Set headers first, then WriteHeader, then the body.

  108. 108. Why should a recover middleware not be your only protection against panics in a server that starts its own goroutines?

    Answer: A recover only catches a panic in its own goroutine, so a panic in a goroutine you started still crashes the process

    Each goroutine has its own stack, and recover works only in a deferred call on the panicking goroutine. A goroutine you launch needs its own defer with recover.

  109. 109. You run go get github.com/go-chi/chi/v5. Which files change?

    Answer: go.mod (the requirement) and go.sum (the checksums)

    go.mod records the module and version you need, and go.sum records checksums so every later download can be verified. Commit both.

  110. 110. Package order imports store, and you add an import of order inside store. What happens?

    Answer: The build fails with import cycle not allowed

    Go compiles a package after the packages it imports, so imports must not form a circle. Move the shared type into a lower package, or have the lower package declare a small interface.

  111. 111. What does db.QueryRow(...).Scan(&u.Name) return when no row matches?

    Answer: sql.ErrNoRows, which you check with errors.Is

    No row is not a nil error. QueryRow defers the error to Scan, which returns sql.ErrNoRows. Map it to a 404 in the handler, and treat other errors as a 500.

  112. 112. Listing 20 orders and then running one query per order to load its customer is called what?

    Answer: The N+1 query problem: fix it with a JOIN or one WHERE id = ANY(...) query

    One query for the list plus N for the details. Each round trip costs time, so 21 queries can be far slower than 1 or 2. Load the related rows in one query.

  113. 113. net/http runs each request in its own goroutine. Your handlers share a map[int]User. What do you need?

    Answer: A sync.Mutex (or RWMutex) around every read and write of the map

    Plain maps are not safe for concurrent writes; Go may stop the program with concurrent map writes. Guard the map with a mutex, or keep the data in a database.

  114. 114. Inside a handler, which context should you pass to db.QueryContext?

    Answer: r.Context(), so the query is cancelled when the client goes away

    r.Context() ends when the client disconnects or the server shuts down. Passing it lets the driver cancel the query and free the connection.

  115. 115. A struct has Password string json:"-"` and Email string json:"email,omitempty". You marshal it with Email: ""`. What is in the JSON?

    Answer: Neither field

    json:"-" never writes the field, and omitempty drops the empty string. Neither key appears.

  116. 116. Your store returns fmt.Errorf("get user %d: %w", id, ErrNotFound). How does the handler decide to send a 404?

    Answer: errors.Is(err, ErrNotFound)

    %w wraps the sentinel, so == fails but errors.Is follows the chain and finds it. Comparing message strings breaks the moment someone rewords the error.

  117. 117. You are writing a 300-line tool with one job. Which layout fits?

    Answer: Flat: one package, a few files

    Start flat. Layout should match the size of the problem, and a 300-line tool does not need folders.

  118. 118. Your layer-grouped app (models/, services/, handlers/) has grown to a dozen features and you hit an import cycle. What is the usual next step?

    Answer: Move to one folder per domain, like user/ and order/, each holding its own model, service and handler

    Grouping by layer spreads one feature across many folders and invites cycles. Grouping by domain keeps a feature together and dependencies point one way.

  119. 119. How should Go packages be organised in a service?

    Answer: By domain: user/, note/, each holding its own model, repo, service and handler

    Layer-based layouts mean every feature touches five folders and every package imports every other. A domain package can be read, tested and deleted on its own.

  120. 120. What does the internal/ directory do?

    Answer: The compiler forbids anything outside your module from importing it

    The Go toolchain enforces it. Put everything that is not meant to be a public API under it and you get that boundary for free.

  121. 121. Why does main usually just call a run() error function?

    Answer: Because os.Exit skips deferred calls, so you want exactly one os.Exit, at the top

    With os.Exit scattered through main, your defer db.Close() never runs. One exit point at the top keeps every defer working.

  122. 122. Which is the correct dependency direction?

    Answer: handler → service → repository

    Dependencies point inward. The repository never imports net/http; the service never touches a SQL dialect. That is what makes each layer testable alone.

  123. 123. How should a password be stored?

    Answer: A bcrypt or argon2id hash

    bcrypt is slow on purpose, which makes guessing passwords from a stolen database expensive. SHA-256 is far too fast, and anything reversible defeats the point.

  124. 124. Login fails. Which error should you return?

    Answer: The same generic "invalid credentials" for both

    Different messages let anyone enumerate which emails have accounts. Ideally the timing matches too — hash against a dummy value in the missing-user case.

  125. 125. What protects the payload of a JWT?

    Answer: Nothing — it is base64, readable by anyone. The signature only proves it was not altered.

    Put an id in it, never a secret. The value of a JWT is that your server can trust it without a database lookup, not that it hides anything.

  126. 126. You skip checking the signing method when parsing a JWT. What is the consequence?

    Answer: A complete authentication bypass — an attacker signs their own token with alg: none

    Assert t.Method.(*jwt.SigningMethodHMAC) inside the key function, or pass jwt.WithValidMethods. Current golang-jwt refuses none unless you opt in, but algorithm-confusion bugs have shipped in real products more than once.

  127. 127. Why use an unexported struct type as a context key?

    Answer: A string key can collide with, or be read by, any other package including your dependencies

    ctxKey{} from your package is a different key from anyone else’s, because the types differ. Export typed accessors, never the key.

  128. 128. Why are access tokens only 15 minutes?

    Answer: Because a JWT cannot be revoked — the short window limits how long a stolen one is useful

    Checking a list of cancelled tokens on every request would bring back the database lookup the JWT was meant to avoid. The revocable half is the stored refresh token.

  129. 129. What do you store in the refresh_tokens table?

    Answer: A SHA-256 hash of the token

    Same idea as a password: someone who steals the table gets nothing they can use. SHA-256 is fine here because the token is already high-entropy random, so bcrypt’s slowness buys nothing.

  130. 130. Why should a refresh token be single-use, replaced on every refresh?

    Answer: It makes theft detectable — a token used twice means a bug or a stolen token

    Without rotation you cannot detect theft at all. On a reuse, revoke every refresh token for that user and force a fresh login.

  131. 131. Why validate config like JWT_SECRET inside config.Load()?

    Answer: So a missing secret stops the deploy immediately instead of producing a 500 on the first login

    Fail at startup, not at 3am. A deploy that will not boot is far cheaper than one that boots broken.

  132. 132. Where does the "is this note mine?" check belong?

    Answer: In the SQL: WHERE id = $1 AND user_id = $2

    In the query it is impossible to forget and has no race. In Go, someone will eventually write a query that skips it. This is IDOR, listed first in the OWASP API Security Top 10 (as BOLA).

  133. 133. A user requests someone else’s note. What status should you return?

    Answer: 404 Not Found

    A 403 confirms the resource exists, which leaks information. Not yours and not there should look identical.

  134. 134. In a PATCH request body, how do you tell "the client sent an empty title" from "the client did not mention the title"?

    Answer: Use a *string field — nil means absent

    A pointer’s nil-ness carries the "was it present" bit. map[string]any also works but throws away all your types.

  135. 135. Which test most matters for an API with per-user data?

    Answer: Creating a note as user A, then reading/updating/deleting it as user B — all must be 404

    That single test is what stops you shipping an IDOR. Everything else on the list is nice to have.

  136. 136. How should you test the repository layer?

    Answer: Against a real, throwaway Postgres

    A fake repository only proves your fake works. It cannot catch a mistyped column, a constraint violation, or a NULL you did not handle.

  137. 137. A user submits javascript:alert(1) to shorten. url.Parse returns no error. What should the service do?

    Answer: Reject it: only allow http or https schemes, with a non-empty host

    url.Parse accepts many strings that are not usable web links. Checking the scheme and host is what stops the shortener redirecting people to script URLs.

  138. 138. Why are codes generated with crypto/rand and not math/rand?

    Answer: Codes from math/rand are predictable, so someone could guess links that have not been shared yet

    math/rand is not designed to be unpredictable. For anything a stranger should not guess, use crypto/rand.

  139. 139. The alphabet leaves out look-alike characters such as 0, O, 1, l and I. Why?

    Answer: People read and type codes by hand, and look-alikes cause wrong links

    Every character is valid in a URL path. Leaving out characters people confuse makes codes safe to read aloud or copy from paper, at the cost of a slightly smaller alphabet.

  140. 140. Two requests generate the same random code at the same moment. What actually stops both being saved?

    Answer: The UNIQUE constraint on code, with the duplicate-key error turned into ErrCodeTaken and the save retried with a new code

    A check-then-insert has a gap between the two steps. Only the database constraint decides atomically. The service retries a few times on ErrCodeTaken and treats any other error as a real failure.

  141. 141. The redirect sends 301 Moved Permanently. Later the owner edits where the link points. What happens to people who already visited?

    Answer: Their browsers may keep going to the old destination, because a 301 is cached hard

    Browsers cache a 301 aggressively, often with no expiry. Use 302 unless the link can never change. It also lets you count clicks, because every visit reaches your server.

  142. 142. Where is the Store interface that the service uses declared?

    Answer: In the service package, the one that uses it, with only the methods it needs

    Go interfaces are declared by the consumer. A small interface in the service package means the memory store, the Postgres store and a test fake all satisfy it without importing each other.

  143. 143. The Postgres store gets sql.ErrNoRows when looking up a code. What should it return?

    Answer: The model's own ErrNotFound, the same error the memory store returns

    Translate driver errors at the storage boundary. The handler then checks errors.Is(err, model.ErrNotFound) without knowing which store is behind it.

  144. 144. The create handler reads JSON with json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)). What does MaxBytesReader protect against?

    Answer: A client sending a huge body to use up memory

    It stops reading after the limit and returns an error, so one request cannot make the server buffer gigabytes. Slow headers are what ReadHeaderTimeout is for.

  145. 145. What does go.sum hold?

    Answer: Cryptographic checksums of every module version, making builds reproducible and tamper-evident

    Commit it. Together with go.mod it is why Go needs no separate lockfile.

  146. 146. Go picks which version of a shared dependency?

    Answer: The oldest that satisfies everyone — Minimal Version Selection

    Your build does not change because someone else published a release. Upgrades only happen when you ask for one.

  147. 147. What does CGO_ENABLED=0 give you?

    Answer: A fully static binary with no libc dependency — which is what makes distroless images and cross-compiling work

    It is the flag behind both the ~15MB container image and GOOS=linux GOARCH=arm64 go build needing no toolchain.

  148. 148. You publish a breaking change to your library. What must the module path become?

    Answer: github.com/you/thing/v2

    The major version lives in the import path from v2 onward, so v1 and v2 can coexist in one build.

  149. 149. Which four commands should gate every push?

    Answer: gofmt -l, go vet, go test -race, govulncheck

    Formatted, vetted, race-free and free of known vulnerabilities. govulncheck is low-noise because it only reports vulnerabilities in code you actually call.

  150. 150. Which routers let you keep the standard func(http.ResponseWriter, *http.Request) handler?

    Answer: net/http and chi

    chi is a thin router over net/http, so every standard middleware and httptest still work. gin, echo and fiber each define their own context and handler type.

  151. 151. You see c.JSON(200, gin.H{...}) in a handler. What does that tell you?

    Answer: Every handler is tied to gin — moving away means rewriting them all

    gin.H and *gin.Context only exist in gin. Going to gin is easy; coming back means rewriting every handler signature.

  152. 152. Ordered from most control over the SQL to least, which is right?

    Answer: database/sql → sqlx → sqlc → GORM

    database/sql is raw. sqlx scans for you but keeps your SQL. sqlc generates typed Go from your SQL. GORM writes the SQL for you.

  153. 153. What is the best single reason to add golang.org/x/sync/errgroup?

    Answer: Bounded concurrency with SetLimit plus first-error cancellation, in a few lines

    It turns a 25-line worker pool into about 8 lines and cancels the rest on the first error. It is one of the clearest cases in Go for taking a dependency.

  154. 154. How should you judge whether a package is safe to depend on?

    Answer: Last commit, open issues, what go mod graph pulls in, and govulncheck

    Stars measure attention at some point in the past. What matters is whether it is maintained now and how much it drags into your build.

  155. 155. An unexpected database error reaches your handler. What does the client get?

    Answer: A generic 500, with the detail logged against a request id

    A raw SQL error leaks your table and column names; a stack trace leaks your source paths. Log the detail, return a status.

  156. 156. A request is cancelled because the client disconnected. How should you treat it?

    Answer: Recognise context.Canceled — nobody is waiting, so do not page anyone

    Treating client disconnects as 500s fills your error budget with noise and hides real failures.

  157. 157. What must never appear in a log line?

    Answer: Passwords, tokens, or whole Authorization headers

    It is the easiest way to turn a log store into a breach, and log stores are often readable by far more people than your database.

  158. 158. Why keep /livez and /readyz separate?

    Answer: Liveness means "restart me"; readiness means "stop sending traffic". Merging them makes a brief DB blip restart every instance at once.

    Wire the database ping into readiness only.

  159. 159. Which endpoints deserve the tightest rate limit?

    Answer: Login, register, and password reset

    That is where credential stuffing lands. Rate limiting turns "unlimited guesses" into "twelve a minute". It is some of the cheapest security you can add.

  160. 160. What is wrong with Access-Control-Allow-Origin: * on an authenticated API?

    Answer: Any site can read your API’s responses from a browser, and * is invalid combined with Allow-Credentials: true

    The usual bad fix is to echo back whatever Origin arrives, which does let any site make credentialed calls. Keep an explicit allowlist from config, and set Vary: Origin so a cache does not serve the wrong header to the wrong site.

  161. 161. Which two environment variables should every Go container set?

    Answer: GOMEMLIMIT and GOMAXPROCS

    By default GOGC=100 lets the heap grow to about twice the live heap before the next collection, and the GC knows nothing about your container limit. If live heap plus that headroom passes the limit, the OOM killer ends the process even though most of that memory was garbage. GOMEMLIMIT (set a little below the limit, say 90%) is a soft limit: as the heap nears it the GC runs more often, trading CPU for staying under it. It cannot save you if the live heap itself is too big. Before Go 1.25, without GOMAXPROCS Go used the host’s core count, not your CPU limit: 64 schedulers sharing 2 cores of quota. Go 1.25 and later read the cgroup limit on Linux.

  162. 162. Where should net/http/pprof be exposed?

    Answer: On a separate localhost-only port

    Public pprof leaks your source paths and lets anyone stall your process with a 30-second CPU profile.

  163. 163. What is most often the biggest cause of slow endpoints?

    Answer: A query in a loop, or a missing index

    The database is where your latency lives. One JOIN beats twenty round trips; one index beats a month of Go micro-optimisation.

  164. 164. You want to know whether a change made things faster. What do you run?

    Answer: go test -bench=. -count=10 both times, then benchstat old.txt new.txt

    A single benchmark run is noise. benchstat tells you whether the difference is statistically real.

  165. 165. Which optimisation should you apply without a profile first?

    Answer: Preallocating with make([]T, 0, n) when you already know n

    Preallocation costs nothing in readability and is obviously right. The other three each need a benchmark proving they help in your workload, or they only add risk.

  166. 166. Find the bug: resp, err := client.Do(req); if err != nil { return err }; if resp.StatusCode != 200 { return fmt.Errorf("status %d", resp.StatusCode) }

    Answer: resp.Body is never closed, so every call leaks a connection; add defer resp.Body.Close() right after the error check

    A response body must always be closed, even when you do not read it. Draining it with io.Copy(io.Discard, resp.Body) before closing also lets the connection be reused.

  167. 167. A batch endpoint does for _, item := range req.Items { go process(item) }. One request has 50,000 items. What is the right fix?

    Answer: Cap concurrency with a fixed pool, a semaphore channel, or errgroup with SetLimit, and wait for the work to finish

    Goroutines are cheap, but what they do is not: 50,000 at once can exhaust database connections, memory or a downstream API. Unbounded fan-out also never reports errors. Bound it and wait.

  168. 168. They ask "why would you choose Go?" What is the strongest answer?

    Answer: One static binary, concurrency built in, fast builds, a big standard library — then name the cost

    "It is fast" invites a benchmark argument you cannot win. Naming a real strength and then its cost is what shows judgement.

  169. 169. They ask something you have never used. What do you do?

    Answer: Say you have not used it, then reason out loud about how you would expect it to work

    One confident wrong answer can undo several good ones. "I have not used that, I would expect X because Y — is that close?" sounds honest and thoughtful.

  170. 170. In a live coding round, what loses the most marks in Go?

    Answer: Ignoring errors with _, no ctx, and unbounded goroutines

    They are hiring someone whose code the team will maintain. Error handling, context and bounded concurrency are what they mark.

  171. 171. What should you do before writing any code in a live round?

    Answer: Restate the problem, ask about scale and input, and say your plan out loud

    A good solution to a different question still fails the round. Thinking silently teaches them nothing about you.

  172. 172. One of the most common Go live-coding questions is some form of:

    Answer: Fetch N URLs at the same time with a limit on how many run at once

    It tests goroutines, bounded concurrency, error handling and context in one small problem. errgroup with SetLimit is the short answer.

  173. 173. How should you describe a project you built?

    Answer: What it does, how it is laid out, one decision and its cost, one thing you would change

    Naming what a decision cost you is the sentence they are listening for. A list of technologies tells them nothing about your judgement.

  174. 174. They ask how you stop one user reading another user’s data. Best answer?

    Answer: Put AND user_id = $2 in the query itself

    In the query you cannot forget it and there is no race. UUIDs only hide the problem: that is security through obscurity, not a fix.

  175. 175. They say "this endpoint is slow". What is the first thing you say?

    Answer: "I would measure first — profile it and count the database round trips."

    Guessing is the wrong instinct and they are testing for it. Most often it turns out to be N+1 queries or a missing index, not Go code.

  176. 176. What should you say about interfaces to sound like someone who has maintained Go?

    Answer: Do not add an interface until there is a second implementation or a test that needs a fake

    A one-implementation interface is pure indirection. Saying this marks you apart from people bringing Java habits into Go.

  177. 177. What is worth asking the interviewer at the end?

    Answer: "Is the Go code laid out by domain or by layer?" and "do you run the race detector in CI?"

    Those two answers tell you a lot about the codebase you would inherit, and asking them shows you know what matters.

  178. 178. Which sentence is the strongest thing to say in any design answer?

    Answer: "I chose X, it cost me Y, and here is when I would switch."

    Every design choice has a cost. Naming yours is what separates a senior answer from a memorised one.

  179. 179. A logged-in customer tries to create a product. What status should they get?

    Answer: 403 Forbidden

    Authentication passed, so we know who they are, but they may not do this. 401 means we do not know you; 403 means we do, and the answer is still no.

  180. 180. Why does order_items copy the product name and price instead of pointing at the product?

    Answer: So that changing a product’s price does not silently rewrite past orders

    An order must show what was paid at the time. Anything it points at can change; anything it copies cannot.

  181. 181. What must happen before you read a single byte of an upload?

    Answer: http.MaxBytesReader on the body

    Cap the body first, or a 4GB upload takes the process down before any of your other checks run.

  182. 182. How should you decide what type an uploaded file really is?

    Answer: http.DetectContentType on the first 512 bytes

    Extension and header are both set by the client, so both can lie. Sniffing reads the actual magic bytes. It is a type check, not a malware check.

  183. 183. The file is written to disk but the database insert fails. What do you do?

    Answer: os.Remove the file, then return the error

    Otherwise you build up files nothing points at, forever. Clean up on the failure path.

  184. 184. Adding a product already in the cart should increase the quantity. What is the best way?

    Answer: INSERT ... ON CONFLICT (user_id, product_id) DO UPDATE

    One statement, no race between the check and the write. The UNIQUE constraint is what makes it work.

  185. 185. Two customers check out the last item at the same moment. What prevents overselling?

    Answer: Putting the condition in the UPDATE: WHERE id = $2 AND stock >= $1, then checking RowsAffected

    Check-then-update leaves a gap where both requests see "1 left". Putting the condition in the WHERE clause makes the check and the change one statement.

  186. 186. Why does the checkout function use a named return value for its error?

    Answer: So the deferred rollback can see whether an error happened

    defer func() { if err != nil { tx.Rollback() } }() needs to read the error the function is returning. This is one of the few places where naming a return earns its keep.

  187. 187. Which of these must never happen inside a transaction?

    Answer: Calling a payment provider over HTTP

    A transaction holds a pooled connection for its whole life. A slow third party then ties that connection up, and enough of them use up the pool.

  188. 188. Why set X-Content-Type-Options: nosniff when serving uploaded images?

    Answer: It stops the browser guessing the type and running a file you did not mean to be code

    Some browsers ignore your Content-Type and guess from the contents. That guessing is what turns a stored file into script running on your own domain.

  189. 189. Why store uploads behind a small Storage interface with Save, Open and Remove?

    Answer: So swapping local disk for S3 later is a second implementation, not a refactor

    Local disk stops working the moment you run more than one instance. Three methods behind an interface is what makes that a contained change.

  190. 190. What should the stored filename be?

    Answer: A random name you generate with crypto/rand

    Go already strips directory parts from multipart filenames, but a client name can still collide with, and overwrite, another upload, or carry characters your filesystem dislikes. Generate the name yourself and keep the original only as display text.

  191. 191. Why io.Copy(out, file) rather than io.ReadAll?

    Answer: It streams through a small buffer, so memory stays constant regardless of file size

    ReadAll pulls the whole file into memory — ten concurrent 10MB uploads is 100MB of heap. Streaming is what io.Reader/io.Writer exist for.