Mixed final test
Every question from every section. Save this one for just before an interview.
What is the value of city after var city string?
All questions with explanations (answers shown)
1. What is the value of
cityaftervar city string?Answer:
""— the empty stringEvery type has a zero value and a string’s is
"". Only pointers, slices, maps, channels, funcs and interfaces arenil. Go has noundefined.2. Which of these does NOT compile?
Answer:
var b float64 = someIntGo never converts between typed numeric values implicitly. You must write
float64(someInt). Only untyped constants like25adapt to the type they are assigned to.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. Which verb prints the type of a value, such as
intorstring?Answer:
%T%Tprints the type:fmt.Printf("%T", 3.5)givesfloat64.%vprints the value,%sa string, and%qa quoted string.%Tis the quickest way to check what type Go inferred for a:=variable.5. What does
fmt.Println(7 / 2)print?Answer:
3Both operands are integers, so this is integer division and it truncates toward zero. If you want
3.5, convert first:float64(7) / 2.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 needstrconv.Itoa(65).go vetflags the common form of this mistake.7. Which loop keyword does Go have?
Answer: Only
forThere is one loop keyword. Drop the init and post clauses and
foris a while loop; drop everything and it is infinite.8. In a Go
switch, when do you needbreakat 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. What does
var i int8 = 127; i++leave ini?Answer:
-128Integer overflow wraps around with no panic and no warning. Narrowing conversions truncate the same way (
int8(x)withx := 200gives-56), so check the range before converting to a smaller type.10. How does Go report that something went wrong?
Answer: A returned
errorvalue you must checkErrors are ordinary values returned alongside the result. Panic is reserved for broken assumptions, not for expected failures.
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 arraySlicing does not copy. Both slices point into the same backing array, so a write through one is visible through the other. Use
copywhen you need independence.12. What does
len("héllo")return?Answer:
6lenon a string counts bytes, andéis two bytes in UTF-8. For characters you wantutf8.RuneCountInString, orrange, which decodes for you.13. You read
v := m["missing"]from amap[string]int. What happens?Answer:
vis0, the zero valueA 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. A function returns
error. Inside it you wrotevar e *MyError = nil; return e. The caller checkserr != nil. What do they see?Answer:
true— the interface holds a type, so it is not nilThis 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 literalnil.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. 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.Mutexcopies the lock, which is a buggo vetcatches.17. What does
%wdo infmt.Errorf("get user %d: %w", id, err)?Answer: Wraps it so
errors.Isanderrors.Ascan still see the original%wpreserves the error chain.%vflattens it to text and breakserrors.Is, which is sometimes what you want: it hides an internal error from callers.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
deferfires 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. A struct field is named
email(lowercase). What doesjson.Marshaldo 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. Why is
out += xinside a loop over 100,000 strings slow?Answer: Strings are immutable, so each
+=allocates and copies the whole stringImmutability makes it O(n²).
strings.Builder(orstrings.Join) writes into one growing buffer instead.21. What is the idiomatic Go test structure?
Answer: A table of cases, looped over with
t.Runfor named subtestsTable-driven tests make the twelfth case one line, and
t.Runlets you run just one withgo test -run "TestX/case_name".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 2ahas spare capacity, so both appends write into the same backing array at index 3, and the second overwrites the first.bandcshare that slot. Never append to one slice from two places.23.
s := []int{1,2,3,4,5}; t := s[1:3:3]; t = append(t, 99). What issafterwards?Answer:
[1 2 3 4 5]The full slice expression
s[1:3:3]sets the capacity oftto3-1 = 2, soappendhas no room and copies to a new array.sis untouched. Without the third index,appendwould have overwrittens[3]with 99.24. What does this print?
x := 1; defer fmt.Println(x); x = 2Answer:
1A deferred call’s arguments are evaluated when the `defer` statement runs, not when the call fires.
xwas 1 then. To see the later value, defer a closure:defer func() { fmt.Println(x) }().25.
m := map[string]int{"a":1,"b":2,"c":3}. What doesfor 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.
var p *bytes.Buffer; var w io.Writer = p; fmt.Println(w == nil). What prints?Answer:
falsewholds a type (*bytes.Buffer) and a nil pointer value. An interface is nil only when it has no type at all, sow == nilis false. This is the same trap as returning a typed nilerror.27. What makes an identifier visible outside its package?
Answer: Starting it with a capital letter
Capitalisation is the access modifier.
Printlnis exported;printlnwould be package-private. There is nopublicorprivatekeyword.28. What does
for i := 0; i < 3; i++ { defer fmt.Print(i) }print when the function returns?Answer:
210Deferred calls run last-in, first-out, and the argument
iis evaluated when thedeferline runs, not when the call fires. So the values 0, 1, 2 are saved and printed in reverse.29.
m := map[string]int{}thenv, ok := m["x"]. What arevandok?Answer:
0 falseReading 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.
a := []int{1, 2, 3},b := a[:2],b = append(b, 9). What isanow?Answer:
[1 2 9]bsharesa’s backing array and still has spare capacity (3), soappendwrites 9 into the slota[2]already uses instead of allocating a new array.31. What is
len("héllo")?Answer:
6lenon a string counts bytes, not characters.étakes two bytes in UTF-8, so five characters make six bytes. Useutf8.RuneCountInStringto count runes.32.
func inc(n int) { n++ }, thenx := 1; inc(x); fmt.Println(x). What prints?Answer:
1Go passes arguments by value, so
incchanges its own copy. To changex, take a*intand write*n++, calling it asinc(&x).33.
type P struct{ X, Y int }. What doesP{1, 2} == P{1, 2}give?Answer:
trueStructs 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.
n, err := strconv.Atoi("12a"). What do you get?Answer:
nis 0 anderris non-nilErrors are returned values, not exceptions. On failure the number comes back as its zero value and
errexplains what went wrong, so you checkerrbefore usingn.35.
const ( A = iota * 10; B; C ). What isC?Answer:
20Each line in the block repeats the last expression with
iotagoing up by one.Cis on line 2, so it is2 * 10.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
recoveronly does something there. Called in normal code it just returnsnil.37.
switch x := 2; x { case 1: fmt.Print("a"); case 2: fmt.Print("b"); case 3: fmt.Print("c") }. What prints?Answer:
bGo cases do not fall through. Only the matching case runs, unless you write
fallthroughon purpose.38.
var p *MyErr = nil, thenvar err error = p. What iserr == nil?Answer:
falseAn interface is nil only when both its type and its value are empty.
errholds the type*MyErrwith a nil value, so it is not nil. Return a plainnilfrom functions instead of a typed nil pointer.39.
type Counter struct{ n int }withfunc (c Counter) Inc() { c.n++ }. Aftervar c Counter; c.Inc(), what isc.n?Answer:
0A value receiver gets a copy, so
Incbumps the copy and throws it away. Use a pointer receiver(c *Counter)when a method must change the value.40.
var v any = 3.0, then a type switch withcase int,case float64anddefault. Which case runs?Answer:
float64An untyped float constant like
3.0becomesfloat64when stored in an interface. A type switch matches the dynamic type exactly, with no conversion.41.
err := fmt.Errorf("load: %w", ErrNotFound). What iserrors.Is(err, ErrNotFound)?Answer:
true%wwraps the error and keeps it in the chain.errors.Iswalks that chain, so it findsErrNotFoundeven though==would fail.42. Which name can code in a different package use?
Answer:
UserNameGo has no
publickeyword. A name is exported only when it starts with an uppercase letter.43.
type U struct{ Name string; age int }. What doesjson.Marshal(U{"Ann", 30})produce?Answer:
{"Name":"Ann"}encoding/jsoncan only see exported fields, soageis skipped without any error. Without a tag the key is the field name exactly as written.44. Which test will
go testfind and run?Answer:
func TestAdd(t *testing.T)inadd_test.goA test lives in a file ending
_test.go, its name starts withTestfollowed by a non-lowercase letter, and it takes exactly one*testing.T.45. In what order does
for k := range mvisit 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.
type S struct{},func (s *S) M() {},type I interface{ M() }. What happens withvar _ I = S{}?Answer: Compile error:
Sdoes not implementIbecauseMhas a pointer receiverOnly
*Shas the methodM, so a plainSvalue does not satisfyI. Writing&S{}fixes it.47.
var b byte = 255; b++. What isb?Answer:
0byteisuint8. Integer overflow at run time wraps around silently, so 255 + 1 becomes 0.48. Two sum with a
map[int]intfrom 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.
a := []int{1, 2, 3, 4}; b := a[1:3]; slices.Reverse(b); fmt.Println(a)prints:Answer:
[1 3 2 4]bsharesa's backing array, so reversingbswaps the middle two elements ofa. Useslices.Clonewhen you need an independent copy.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), noth.Push(x).51. Inside
for i, r := range sover a string, what areiandr?Answer:
iis the byte offset,ris a runeRanging over a string decodes UTF-8.
ijumps by the size of each character in bytes.s[i]would give a byte, not a rune.52.
i := sort.SearchInts(s, x)andxis bigger than every element. What must you do before readings[i]?Answer: Check
i < len(s), because it returnslen(s)sort.Searchand its helpers return n when the condition is never true. Readings[n]panics.53. In an LRU cache built with
container/listand 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. 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; saveslices.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.
dp := make([][]int, n)and thendp[0][0] = 1. What happens?Answer: It panics: each row is a nil slice until you
makeitmake([][]int, n)makes n nil rows. Loop andmakeeach row before you index into it.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. 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 == falseimmediately.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. What does receiving from a nil channel do?
Answer: Blocks forever
It blocks forever, and that is useful. Setting a channel variable to
nilinside aselectdisables that case, which is the standard way to drop a branch out of a loop.60. Where must
wg.Add(1)go?Answer: Before the
gostatementInside the goroutine it races with
Wait, which can see a count of zero and return before anything started.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. 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. Where should a
context.Contextlive?Answer: The first parameter of the function, named
ctxA 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. What is
context.Valuefor?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. 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. 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. What does a
selectwith adefaultcase do when no channel is ready?Answer: Runs
defaultimmediatelyA
defaultmakes theselectnon-blocking. Without one it waits until some case is ready, choosing at random among those that are.68.
ch := make(chan int, 1); ch <- 7; close(ch). What do two receivesv, ok := <-chgive?Answer:
7 true, then0 falseClosing does not discard buffered values. You drain
7withok == true, then every later receive returns the zero value withok == falseimmediately. That is howfor v := range chknows to stop.69. In a
selectloop, one case receives fromin, which isnil. 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
selectthat case simply never fires. Setting a drained channel tonilis the standard way to switch off one case while the others keep running. Only aselectwhose cases are *all* nil, with nodefault, blocks forever.70.
mainrunsgo fmt.Println("hi")and then returns straight away. What happens?Answer: Most likely nothing prints, because the program exits when
mainreturnsThe program ends as soon as
mainreturns and does not wait for other goroutines. Use async.WaitGroupor a channel to wait.71.
ch := make(chan int), thench <- 1inmainwith 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.
ch := make(chan int, 1); ch <- 7; close(ch); a := <-ch; b, ok := <-ch. What area,bandok?Answer:
7 0 falseClosing does not throw away buffered values, so
agets 7. After that the channel is empty and closed, so receives give the zero value andokis false.73. Which command reports data races while your tests run?
Answer:
go test -raceThe 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. After
ctx, cancel := context.WithCancel(parent)andcancel(), what doesctx.Err()return?Answer:
context.CanceledOnce a context is done,
Errsays why. A manual cancel givescontext.Canceled; a passed deadline or timeout givescontext.DeadlineExceeded.75. Why call
wg.Add(1)before thegostatement instead of inside the new goroutine?Answer:
Waitcould run before the goroutine callsAdd, see a zero counter and return earlyWaitreturns when the counter is zero. If the goroutine has not started yet, the counter may still be zero. Adding first removes that race.76.
chis an empty channel. What doesselect { case v := <-ch: fmt.Print(v); default: fmt.Print("none") }do?Answer: Prints
noneright awayA
selectwith adefaultnever blocks. If no case is ready at that moment,defaultruns.77. Several goroutines write to the same plain
mapwith no lock. What can happen?Answer: The program can crash with
fatal error: concurrent map writesBuilt-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 usesync.Mapfor the cases it fits.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. On Go 1.22 or later,
for i := 0; i < 3; i++ { wg.Add(1); go func() { defer wg.Done(); fmt.Print(i) }() }followed bywg.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. What does
~intmean in a constraint?Answer: Any type whose underlying type is int, so
type UserID intqualifiesWithout the tilde, only
intitself satisfies it — your own named types would not.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.
Shapeis an interface.Sum[T Number]is a generic.82. Which package should you use for random values in a security token?
Answer:
crypto/randmath/randis 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. 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
slicesandmapsfirst: much of what people hand-roll is already there.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.anyallows every type, andcomparableonly guarantees==and!=, so both are rejected.cmp.Orderedis the constraint for<and>. (For two values, the built-inmaxalready exists.)85.
type Celsius float64. Which constraint letsSum[T]accept a[]Celsius?Answer:
interface{ ~float64 }~float64means "any type whose underlying type is float64", which includesCelsius. Plainfloat64matches onlyfloat64itself.anywould acceptCelsiusbut would not allow+in the body.86. What does
for i := range 3 { fmt.Print(i) }print in Go 1.22+?Answer:
012Since Go 1.22 you can range over an integer
n, which yields0up ton-1. It is the short form offor i := 0; i < 3; i++.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
ServeMuxmatched paths only, so you routed methods by hand. Nowr.PathValue("id")gets the parameter and the framework buys you very little.88. What is the correct order inside a handler?
Answer: Set headers, then
WriteHeader, then write the bodyHeaders set after
WriteHeaderare silently dropped, and writing a body impliesWriteHeader(200). Alwaysreturnright after writing an error, or you get "superfluous WriteHeader".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.ServerwithReadHeaderTimeout(the Slowloris defence),ReadTimeout,WriteTimeoutandIdleTimeout.90. What is a middleware in Go?
Answer: A function taking an
http.Handlerand returning anhttp.HandlerThat is the whole mechanism. You compose by nesting, so no framework is required.
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. Why must
signal.Notify’s channel be buffered?Answer:
signal.Notifynever blocks, so an unbuffered channel with nobody receiving yet drops the signalmake(chan os.Signal, 1). Get this wrong and your graceful shutdown silently never triggers.93. A handler calls
w.Write(body)and thenw.WriteHeader(http.StatusCreated). What does the client get?Answer: 200 OK, and the server logs "superfluous response.WriteHeader call"
The first
Writesends a 200 if no status was set. After that the status is fixed, so the laterWriteHeaderonly produces a log line. CallWriteHeader(201)before writing the body.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 foreverWith no timeouts, a slow client (Slowloris) can keep many connections open by trickling headers.
ReadHeaderTimeoutcloses them. SetReadTimeout,WriteTimeoutandIdleTimeouttoo.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. What is the default value of
SetMaxOpenConnsif you never call it?Answer: Unlimited
Unlimited, so a traffic spike keeps opening connections until Postgres hits
max_connectionsand refuses new ones. The pool limit is your backpressure. Always set it.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. After looping with
rows.Next(), what must you not forget?Answer:
defer rows.Close()and checkingrows.Err()Without
Closeyou leak a pooled connection, and iteration errors surface only throughrows.Err(): the loop just ends early and looks successful.99. You call
repo.GetUseronce 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. 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. 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. Why should you never write
SELECT *?Answer: Adding a column breaks every
Scanat once, with an unhelpful errorScanmatches columns positionally. List the columns and a new one changes nothing.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 earlyreturninside the loop leaks a pooled connectionrowsholds a connection until it is closed. WhenNextreturns false the rows close themselves, but any early return skips that. Putdefer rows.Close()right after the error check.104. A list query sometimes returns fewer rows than expected, with no error. The loop is
for rows.Next() { ... }and thenreturn 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 resultsNextreturns false both at the end and on an error. Onlyrows.Err()tells them apart. Return it after the loop.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
Sprintfis 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. 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 awaycontext.Background()is never cancelled.r.Context()is cancelled when the client disconnects, and the driver then cancels the query and frees the connection.107. A handler calls
w.Write([]byte("ok"))and thenw.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
Writesends the status line and headers. Anything you set on the header map afterwards is ignored. Set headers first, thenWriteHeader, then the body.108. Why should a recover middleware not be your only protection against panics in a server that starts its own goroutines?
Answer: A
recoveronly catches a panic in its own goroutine, so a panic in a goroutine you started still crashes the processEach goroutine has its own stack, and
recoverworks only in a deferred call on the panicking goroutine. A goroutine you launch needs its owndeferwithrecover.109. You run
go get github.com/go-chi/chi/v5. Which files change?Answer:
go.mod(the requirement) andgo.sum(the checksums)go.modrecords the module and version you need, andgo.sumrecords checksums so every later download can be verified. Commit both.110. Package
orderimportsstore, and you add an import oforderinsidestore. What happens?Answer: The build fails with
import cycle not allowedGo 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. What does
db.QueryRow(...).Scan(&u.Name)return when no row matches?Answer:
sql.ErrNoRows, which you check witherrors.IsNo row is not a nil error.
QueryRowdefers the error toScan, which returnssql.ErrNoRows. Map it to a 404 in the handler, and treat other errors as a 500.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(...)queryOne 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. net/http runs each request in its own goroutine. Your handlers share a
map[int]User. What do you need?Answer: A
sync.Mutex(orRWMutex) around every read and write of the mapPlain 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. Inside a handler, which context should you pass to
db.QueryContext?Answer:
r.Context(), so the query is cancelled when the client goes awayr.Context()ends when the client disconnects or the server shuts down. Passing it lets the driver cancel the query and free the connection.115. A struct has
Password stringjson:"-"`andEmail stringjson:"email,omitempty". You marshal it withEmail: ""`. What is in the JSON?Answer: Neither field
json:"-"never writes the field, andomitemptydrops the empty string. Neither key appears.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)%wwraps the sentinel, so==fails buterrors.Isfollows the chain and finds it. Comparing message strings breaks the moment someone rewords the error.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. 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/andorder/, each holding its own model, service and handlerGrouping by layer spreads one feature across many folders and invites cycles. Grouping by domain keeps a feature together and dependencies point one way.
119. How should Go packages be organised in a service?
Answer: By domain:
user/,note/, each holding its own model, repo, service and handlerLayer-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. 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. Why does
mainusually just call arun() errorfunction?Answer: Because
os.Exitskips deferred calls, so you want exactly oneos.Exit, at the topWith
os.Exitscattered throughmain, yourdefer db.Close()never runs. One exit point at the top keeps every defer working.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. 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. 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. 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. 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: noneAssert
t.Method.(*jwt.SigningMethodHMAC)inside the key function, or passjwt.WithValidMethods. Currentgolang-jwtrefusesnoneunless you opt in, but algorithm-confusion bugs have shipped in real products more than once.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. 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. What do you store in the
refresh_tokenstable?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. 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. Why validate config like
JWT_SECRETinsideconfig.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. Where does the "is this note mine?" check belong?
Answer: In the SQL:
WHERE id = $1 AND user_id = $2In 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. 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. 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
*stringfield —nilmeans absentA pointer’s nil-ness carries the "was it present" bit.
map[string]anyalso works but throws away all your types.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. 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. A user submits
javascript:alert(1)to shorten.url.Parsereturns no error. What should the service do?Answer: Reject it: only allow
httporhttpsschemes, with a non-empty hosturl.Parseaccepts many strings that are not usable web links. Checking the scheme and host is what stops the shortener redirecting people to script URLs.138. Why are codes generated with
crypto/randand notmath/rand?Answer: Codes from
math/randare predictable, so someone could guess links that have not been shared yetmath/randis not designed to be unpredictable. For anything a stranger should not guess, usecrypto/rand.139. The alphabet leaves out look-alike characters such as
0,O,1,landI. 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. Two requests generate the same random code at the same moment. What actually stops both being saved?
Answer: The
UNIQUEconstraint oncode, with the duplicate-key error turned intoErrCodeTakenand the save retried with a new codeA check-then-insert has a gap between the two steps. Only the database constraint decides atomically. The service retries a few times on
ErrCodeTakenand treats any other error as a real failure.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. Where is the
Storeinterface 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. The Postgres store gets
sql.ErrNoRowswhen looking up a code. What should it return?Answer: The model's own
ErrNotFound, the same error the memory store returnsTranslate driver errors at the storage boundary. The handler then checks
errors.Is(err, model.ErrNotFound)without knowing which store is behind it.144. The create handler reads JSON with
json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)). What doesMaxBytesReaderprotect 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
ReadHeaderTimeoutis for.145. What does
go.sumhold?Answer: Cryptographic checksums of every module version, making builds reproducible and tamper-evident
Commit it. Together with
go.modit is why Go needs no separate lockfile.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. What does
CGO_ENABLED=0give 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 buildneeding no toolchain.148. You publish a breaking change to your library. What must the module path become?
Answer:
github.com/you/thing/v2The major version lives in the import path from v2 onward, so v1 and v2 can coexist in one build.
149. Which four commands should gate every push?
Answer:
gofmt -l,go vet,go test -race,govulncheckFormatted, vetted, race-free and free of known vulnerabilities.
govulncheckis low-noise because it only reports vulnerabilities in code you actually call.150. Which routers let you keep the standard
func(http.ResponseWriter, *http.Request)handler?Answer:
net/httpand chichi is a thin router over
net/http, so every standard middleware andhttpteststill work. gin, echo and fiber each define their own context and handler type.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.Hand*gin.Contextonly exist in gin. Going to gin is easy; coming back means rewriting every handler signature.152. Ordered from most control over the SQL to least, which is right?
Answer: database/sql → sqlx → sqlc → GORM
database/sqlis raw.sqlxscans for you but keeps your SQL.sqlcgenerates typed Go from your SQL. GORM writes the SQL for you.153. What is the best single reason to add
golang.org/x/sync/errgroup?Answer: Bounded concurrency with
SetLimitplus first-error cancellation, in a few linesIt 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. How should you judge whether a package is safe to depend on?
Answer: Last commit, open issues, what
go mod graphpulls in, andgovulncheckStars 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. 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. A request is cancelled because the client disconnected. How should you treat it?
Answer: Recognise
context.Canceled— nobody is waiting, so do not page anyoneTreating client disconnects as 500s fills your error budget with noise and hides real failures.
157. What must never appear in a log line?
Answer: Passwords, tokens, or whole
AuthorizationheadersIt 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. Why keep
/livezand/readyzseparate?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. 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. 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 withAllow-Credentials: trueThe usual bad fix is to echo back whatever
Originarrives, which does let any site make credentialed calls. Keep an explicit allowlist from config, and setVary: Originso a cache does not serve the wrong header to the wrong site.161. Which two environment variables should every Go container set?
Answer:
GOMEMLIMITandGOMAXPROCSBy default
GOGC=100lets 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, withoutGOMAXPROCSGo 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. Where should
net/http/pprofbe 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. 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. You want to know whether a change made things faster. What do you run?
Answer:
go test -bench=. -count=10both times, thenbenchstat old.txt new.txtA single benchmark run is noise.
benchstattells you whether the difference is statistically real.165. Which optimisation should you apply without a profile first?
Answer: Preallocating with
make([]T, 0, n)when you already know nPreallocation 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. 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.Bodyis never closed, so every call leaks a connection; adddefer resp.Body.Close()right after the error checkA 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. 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
errgroupwithSetLimit, and wait for the work to finishGoroutines 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. 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. 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. In a live coding round, what loses the most marks in Go?
Answer: Ignoring errors with
_, noctx, and unbounded goroutinesThey are hiring someone whose code the team will maintain. Error handling, context and bounded concurrency are what they mark.
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. 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.
errgroupwithSetLimitis the short answer.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. They ask how you stop one user reading another user’s data. Best answer?
Answer: Put
AND user_id = $2in the query itselfIn 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. 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. 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. 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. 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. 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. Why does
order_itemscopy 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. What must happen before you read a single byte of an upload?
Answer:
http.MaxBytesReaderon the bodyCap the body first, or a 4GB upload takes the process down before any of your other checks run.
182. How should you decide what type an uploaded file really is?
Answer:
http.DetectContentTypeon the first 512 bytesExtension 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. The file is written to disk but the database insert fails. What do you do?
Answer:
os.Removethe file, then return the errorOtherwise you build up files nothing points at, forever. Clean up on the failure path.
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 UPDATEOne statement, no race between the check and the write. The UNIQUE constraint is what makes it work.
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 checkingRowsAffectedCheck-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. 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. 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. Why set
X-Content-Type-Options: nosniffwhen 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. Why store uploads behind a small
Storageinterface withSave,OpenandRemove?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. What should the stored filename be?
Answer: A random name you generate with
crypto/randGo 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. Why
io.Copy(out, file)rather thanio.ReadAll?Answer: It streams through a small buffer, so memory stays constant regardless of file size
ReadAllpulls the whole file into memory — ten concurrent 10MB uploads is 100MB of heap. Streaming is whatio.Reader/io.Writerexist for.