Go · Quick revision
All 101 Go topics, condensed
The main points from every topic, in the order you learnt them. Open the ones you want, or open everything and read straight down.
Getting started
- ·A module is a folder with a
go.mod. A runnable program ispackage mainwithfunc main(). - ·Every variable has a zero value. There is no undefined, and no unset variable to guard against.
- ·
:=inside functions,varwhen you want the type written down or you are at package level. - ·
go run,go build,go fmt,go vet. That is the whole daily toolchain.
Remember: Go compiles to one self-contained binary with nothing to install beside it, and every variable starts at a defined zero value. Those two facts shape most of the language.
Read the full topic →- ·Package, imports, code: in that order, in every file. Semicolons are automatic.
- ·The opening brace must be on the same line, because Go inserts semicolons for you.
- ·Unused imports and unused variables are compile errors, not warnings.
- ·MixedCaps naming, capital means exported, initialisms stay uppercase (
userID,parseURL).
Remember: Capitalisation is not style in Go. It is the access modifier.
Read the full topic →- ·
Printlnfor quick output,Printffor formatted,Sprintfto build a string. - ·
%vis the default for any value,%Tshows the type. - ·
Printfneeds its own\n;Printlnadds one for you. - ·The
Sprefix (Sprintf,Sprintln) returns a string instead of printing it.
Remember:
Read the full topic →%v prints anything and %T tells you its type. Learn them before you learn a debugger.- ·
intfor counting,int64for ids,float64for decimals, never a float for money. - ·Overflow wraps silently. That is why every conversion between sizes is explicit.
- ·
byteisuint8andruneisint32. The aliases exist to show intent. - ·Every type starts at its zero value:
0,""orfalse.
Remember: Go gives you exact-size types for when it matters, and
Read the full topic →int for when it does not.- ·A constant is fixed at compile time. The compiler enforces it; it is not a promise.
- ·A constant without a written type adapts to where it is used; a typed one does not.
- ·
iotacounts up from 0 through a const block, and you can do maths with it. - ·Go has no
enumkeyword. A const block withiotanumbers a set of choices.
Remember: There are no constant slices, maps or structs. Those are
Read the full topic →var.- ·Integer division truncates. Convert to float64 first if you want a decimal.
- ·Comparisons give a
bool, and both sides must be the same type. - ·
&&and||short-circuit, which is what makesx != nil && x.Fieldsafe. - ·No ternary, no operator overloading, no pointer arithmetic. All three are left out on purpose.
Remember: None of Go’s operators can be redefined.
Read the full topic →a + b means addition, or concatenation for strings, in every file you will ever read.- ·Every conversion between types is written out by you. Go never widens silently.
- ·
float64(a),int64(a),[]byte(s),[]rune(s): all explicit. - ·
lenon a string counts bytes, not characters. - ·The cost of typing the conversion is lower than the cost of finding the bug it prevents.
Remember: Implicit numeric conversion is where money code loses cents. Go makes you write it down.
Read the full topic →- ·One loop keyword:
for. Drop parts of it to get a while loop or an infinite one. - ·
if n := len(s); n > 3scopes the variable to the if and its else. - ·Cases do not fall through, so you never write
break. - ·A
switchwith no expression is the idiomatic if/else chain.
Remember: There is no ternary operator. Write the
Read the full topic →if.Core language
- ·Errors are ordinary return values. There are no exceptions and no hidden jumps.
- ·
if err != nil { return ... }right after the call. Handle it and return early. - ·Always add context when you pass an error up. A bare
return errloses the trail. - ·Functions are values: they can be passed, returned, and can capture their surroundings.
Remember: An error is a value, not an event. Every failure point is visible in the code you are reading.
Read the full topic →- ·
deferruns when the function returns, not when the block ends. LIFO order. - ·Arguments are evaluated immediately; only the call happens later.
- ·
deferinside a loop does not run until the whole function ends. - ·A deferred closure can modify a named return value. Rollback helpers rely on this.
Remember: defer puts cleanup next to the thing that needs cleaning up, and runs it on every return path.
Read the full topic →- ·An array’s length is part of its type. You will rarely use one directly.
- ·A slice is a pointer, a length and a capacity.
appendreturns a new slice, so always reassign. - ·Sub-slices share the backing array, so a write through one is visible through the other.
- ·
copywhen you need independence.s[a:b:b]caps the capacity so the next append reallocates.
Remember: A slice is a window onto an array, not the array itself. Two windows see each other’s writes.
Read the full topic →- ·A missing key returns the zero value, not an error. Use
v, ok := m[k]. - ·Iteration order is randomised on purpose. Sort the keys when order matters.
- ·Writing to a
nilmap panics; reading from one is fine. - ·Maps are not safe for concurrent use. When the runtime detects a concurrent write, it crashes the program on purpose.
Remember: Absent and zero are different things. The two-value form is how you tell them apart.
Read the full topic →- ·
lencounts bytes.rangeand[]runegive you characters. - ·Strings are immutable, so
+=in a loop is O(n²). Usestrings.BuilderorJoin. - ·
Cut,CutPrefix,Fields, andEqualFoldreplace most hand-written parsing. - ·Backtick raw strings for SQL, regexes, and anything with backslashes.
Remember: A string is bytes, not characters. The moment you index or slice one, ask yourself whether you meant a byte or a character.
Read the full topic →- ·
&xtakes an address,*preads and writes through it. - ·Pointers let a function change the caller’s variable instead of a copy.
- ·A
nilpointer can mean "no value", which zero cannot. - ·
makefor slices/maps/channels. No pointer arithmetic, no manual free.
Remember: A pointer is a value holding an address. Go removes the dangerous parts (arithmetic and manual freeing) and keeps the useful part.
Read the full topic →- ·A struct groups fields into one type. Always use field names in a literal.
- ·Assignment and function calls copy a struct. Go has no pass-by-reference.
- ·Taking a pointer (
*User) lets a function change the original instead of a copy.&User{...}makes one, andp.Namedereferences for you. - ·A nil-able pointer field (
*string) separates "not sent" from "sent as empty". - ·Embedding puts one struct inside another; its fields are promoted. Composition, not inheritance.
Remember: Everything in Go is a value and every assignment is a copy.
Read the full topic →- ·A value receiver gets a copy; a pointer receiver can mutate the original.
- ·Pointer receiver when you mutate, the struct is large, or it holds a mutex. Then use it for all methods.
- ·Embedding promotes fields and methods, but it is composition, not inheritance.
- ·An
Adminis not aBase. There are no virtual methods in Go.
Remember: If one method needs a pointer receiver, make them all pointer receivers.
Read the full topic →- ·Interfaces are satisfied implicitly. Any type with the methods qualifies.
- ·The smaller the interface, the more useful. One method is the ideal.
- ·Accept interfaces, return structs, and define the interface where it is used.
- ·An interface holding a nil pointer is not nil. Return the literal
nil.
Remember: Do not create an interface until there is a second implementation or a test that needs a fake.
Read the full topic →- ·
v.(T)gets a T out of an interface, and panics if it is not one. - ·
t, ok := v.(T)never panics.oktells you whether it worked. - ·
switch x := v.(type)checks many types at once; in each casexhas that type. - ·Cases run top to bottom, so put specific types before broad interfaces.
Remember: Comma-ok unless a wrong type is a bug.
Read the full topic →- ·
erroris just an interface with one method. Nothing about it is magic. - ·
errors.Isfor "which error is this",errors.Asfor "give me its data". - ·
%wkeeps the chain soIsandAscan see through it.%vbreaks it, which is sometimes what you want. - ·Handle an error once: log it or return it, not both.
Remember: Add context, do not restate. Say what you were doing, with what.
Read the full topic →- ·Only exported fields are marshalled. A lowercase field is silently missing.
- ·
Unmarshalneeds a pointer, or it has nothing to write into. - ·
json:"-"never serialises;omitemptydrops the field when it is empty. - ·The struct tags are your API’s response shape.
Remember: If a field is missing from your API response, check its first letter.
Read the full topic →- ·A
_test.gofile next to the code, aTestXxx(t *testing.T)function, andgo test. - ·Table-driven tests are the Go standard: cases as data, one loop,
t.Runfor subtests. - ·
go test -run "TestX/case_name"runs one case. The pattern is a regular expression. - ·
t.Errorcontinues;t.Fatalstops that subtest.
Remember: There is nothing to install and nothing to configure. Testing ships with the language.
Read the full topic →Go for coding rounds
- ·Online judges send input on stdin and read your answer from stdout.
- ·
fmt.Scanon bare stdin reads one byte per system call. Wrap stdin inbufio.NewReaderand usefmt.Fscan. - ·Wrap stdout in
bufio.NewWriteranddefer out.Flush(), or the output is lost. - ·
bufio.Scannerstops silently on a line over 64 KB unless you callBuffer. - ·Put the logic in
solve(r io.Reader, w io.Writer)so you can test it withstrings.NewReader.
Remember: Buffered in, buffered out, and Flush before you leave.
Read the full topic →- ·Say the O(n²) brute force, then trade space for time with a map: O(n).
- ·Comma-ok, always, when zero is a meaningful value.
- ·Look up the partner before inserting the current element.
Remember: When the question is "have I seen X before?", the answer is a map.
Read the full topic →- ·Two pointers from the ends for reverse; three reversals for rotate.
- ·Sub-slices share the backing array, so in-place really is in place.
- ·
slices.Reverseexists — use it unless they ask you to write it.
Remember: A slice header is three words. Copying it never copies the elements.
Read the full topic →- ·Map to count, slice to order. Maps never give you order.
- ·Always tie-break, so the output is deterministic.
- ·Heap of size k when k is much smaller than the number of distinct items.
Remember: If the output depends on map order, it is a bug that only fails sometimes.
Read the full topic →- ·Slice as stack:
appendto push,s[:len(s)-1]to pop,s[len(s)-1]to peek. - ·Guard the empty stack before every peek.
- ·Leftover openers at the end mean invalid.
Remember: Any "matching pairs, most recent first" problem is a stack.
Read the full topic →- ·Inclusive
lo..hi, loop whilelo <= hi, mid aslo + (hi-lo)/2. - ·
slices.BinarySearchfor exact lookups;sort.Searchfor lower bound and search-on-answer. - ·Always guard the "returned n" case.
Remember: Binary search works on any monotonic yes/no question, not only on sorted slices.
Read the full topic →- ·Map for O(1) find, doubly linked list for O(1) reorder and evict.
- ·Every
Gethit is a use: move to front. - ·The entry stores its key so eviction can clean up the map.
Remember: When one data structure cannot do both jobs in O(1), use two that point at each other.
Read the full topic →- ·Three pointers:
prev,cur, and the savednext. - ·Save the link before you break it.
- ·Return
prev, notcur.curis nil at the end.
Remember: Draw three boxes and the arrows before you write a line. Pointer bugs are drawing bugs.
Read the full topic →- ·Map of visited nodes first, then two pointers for O(1) space.
- ·Guard both
fastandfast.Next. - ·Compare nodes, not values.
Remember: Two runners on a circular track always meet. On a straight one, the fast one just finishes.
Read the full topic →- ·Dummy head, tail pointer, compare and attach.
- ·Attach the leftover list in one assignment.
- ·O(n + m) time, no new nodes.
Remember: When the first item of a result is a special case, add a dummy in front of it.
Read the full topic →- ·Depth: recursion, nil is 0.
- ·Level order: BFS with a slice queue, one level per round.
- ·Snapshot the queue length before you start a level.
Remember: Depth-first is a stack (or recursion). Breadth-first is a queue. Most tree problems are one of the two.
Read the full topic →- ·Choose, recurse, undo.
- ·Copy the current slice when you save it as an answer.
- ·Output size sets the complexity: 2ⁿ subsets, n! permutations.
Remember: If every answer in your output looks the same, you saved the slice, not a copy of it.
Read the full topic →- ·Recurrence first, code second.
- ·Fill from the smallest case up.
- ·One
makeper row of a 2-D slice.
Remember: If plain recursion recomputes the same small cases again and again, store them. That is all DP is.
Read the full topic →- ·Each cell is a node; its four neighbours are its edges.
- ·Count when you find unvisited land, then flood it.
- ·Bounds check first, then mark visited.
Remember: Any "count the connected groups" question is a flood fill.
Read the full topic →- ·Sort by start, then one pass.
- ·Extend the last interval or start a new one.
- ·Update through a pointer or index, not a copy.
Remember: Most interval problems become easy once they are sorted by start.
Read the full topic →- ·Two edges; the right one always moves, the left one only jumps forward.
- ·Map from character to last index.
- ·Ranging over a string gives byte offsets; convert to
[]runewhen you need character positions.
Remember: If the question says "longest/shortest contiguous ... such that", think sliding window.
Read the full topic →Concurrency
- ·
go f()starts a goroutine. It starts with a few KB of stack, so thousands are normal. - ·The runtime multiplexes them onto a few OS threads and parks them when they block.
- ·You write plain blocking code and the runtime handles the waiting, with no callbacks.
- ·
WaitGroupwaits for a known number.Addbeforego,defer wg.Done()inside.
Remember: When
Read the full topic →main returns the program exits, and every goroutine dies with it.- ·Unbuffered channels synchronise; buffered ones queue. Default to unbuffered.
- ·The sender closes, never the receiver, and only one goroutine may close.
- ·Sending on a closed channel panics; receiving drains what is left, then gives the zero value and
ok=false. - ·A nil channel blocks forever, which is how you disable a
selectcase.
Remember: Know the channel behaviour table cold. Most channel deadlocks and panics are a row in it.
Read the full topic →- ·Mutex for guarding state, channels for transferring ownership. Do not force channels.
- ·Never copy a struct containing a mutex, and never hold a lock across a network call.
- ·A data race is undefined behaviour, not a rare bug.
- ·
go test -race ./...in CI. It finds races that code review and ordinary tests miss.
Remember: Without synchronisation, one goroutine has no guarantee of ever seeing another’s writes.
Read the full topic →- ·First parameter, always, named
ctx. Never stored in a struct. - ·Always
defer cancel(), even on the success path. - ·Cancelling does not stop anything by itself. Your code must select on
ctx.Done(). - ·
context.Valueis for request-scoped identity, not for dependencies or config.
Remember: In a handler, derive from
Read the full topic →r.Context() so a disconnecting client stops your database query too.- ·
sync.Once/sync.OnceValuefor lazy setup that must run exactly once. - ·
wg.Go(f)(Go 1.25) does theAddandDonefor you. - ·
errgroup(golang.org/x/sync) returns the first error, cancels the shared context, andSetLimitcaps parallelism. - ·A worker pool is N goroutines ranging over one jobs channel. The producer closes jobs; a waiter closes results.
- ·A blocked goroutine is never collected. Every goroutine needs a way out: a context, a close, or a buffer.
Remember: Before you type
Read the full topic →go, know how that goroutine will end.- ·Never copy a
syncvalue after first use; pass pointers and letgo vetcheck. - ·
wg.Go(f)(Go 1.25) replaces theAdd/Donepair;Addbeforegoon older versions. - ·
OnceValueandOnceValues(Go 1.21) run setup once and remember the result, including a failure. - ·
sync.Poolis a memory cache that can be emptied at any time. Reset what you get from it. - ·
sync.Mapis for write-once-read-many keys or disjoint key sets; otherwise use a map and a mutex. - ·Typed atomics (Go 1.19) for single values; a mutex as soon as two values must change together.
Remember: Mutex for state, WaitGroup to wait, Once for setup, Pool for scratch memory, atomic for one value, and a channel when data moves.
Read the full topic →- ·A worker pool bounds what runs at once. Goroutines are cheap; the connections and memory they hold are not.
- ·The producer closes
jobs; a goroutine that waits on the WaitGroup closesresults; the reader drainsresults. - ·Send an index with each job to get results back in order.
- ·Cancel a context on the first error or timeout, and make the producer select on it too.
- ·
errgroup.SetLimitor a buffered-channel semaphore gives the same bound with less code for a known list of jobs. - ·Workers: cores for CPU work; throughput × latency for I/O, capped by the downstream limit.
Remember: Bound the work, not the goroutines: N workers, one jobs channel, and every channel closed by the side that knows it is finished.
Read the full topic →Generics and stdlib
- ·A type parameter is a blank filled in at the call site; a constraint says what may fill it.
- ·
~intmeans "any type whose underlying type is int", so your own named types qualify. - ·Generics are for types; interfaces are for behaviour. Do not swap them.
- ·Write it concretely twice before you generalise.
Remember: If the duplication is between behaviours, you wanted an interface, not a generic.
Read the full topic →- ·
for i := range ncounts from 0 to n-1 (Go 1.22). - ·An iterator is a function that calls
yieldfor each value, and stops whenyieldreturns false (Go 1.23). - ·
iter.Seq[V]yields one value per step,iter.Seq2[K, V]yields two. - ·
maps.Keysreturns an iterator.slices.Collectandslices.Sortedturn one into a slice.
Remember: An iterator is just a function you can range over. Always check what yield returns.
Read the full topic →- ·
slices,mapsandcmp(Go 1.21+) replace many hand-written loops. - ·
crypto/randfor anything security-related.math/randis predictable. - ·
go docreads the whole library offline, source included. - ·The stdlib source is clear, idiomatic Go. Read it when you are curious.
Remember: Check the standard library before you write a helper. It is usually already there.
Read the full topic →Web services
- ·Go 1.22
net/httproutes on"GET /users/{id}"and reads params withr.PathValue. No framework needed. - ·A handler is
func(http.ResponseWriter, *http.Request). Everything else is a wrapper over that. - ·Headers, then
WriteHeader, then body. Alwaysreturnafter writing an error. - ·A bare
http.ListenAndServehas no timeouts. Configurehttp.Serveryourself.
Remember: A handler reads the request and writes the response. Everything a framework adds is convenience on top of that one function shape.
Read the full topic →- ·Middleware is
func(http.Handler) http.Handler. Compose by nesting; no framework required. - ·Recover panics at the edge, log the stack, return a clean 500. Panic is for broken assumptions only.
- ·A panic inside a goroutine you started is not recovered by the parent. It kills the process.
- ·
srv.Shutdown(ctx)drains in-flight requests. Buffer the signal channel.
Remember: A handler that wraps another handler is how you extend Go’s HTTP stack, and for an API it covers logging, auth, limits and recovery.
Read the full topic →Modules and packages
- ·Commit
go.modandgo.sum. Minimal Version Selection makes builds reproducible with no lockfile. - ·
go mod tidybefore every commit;go workfor developing two modules together. - ·
CGO_ENABLED=0plusGOOS/GOARCHcross-compiles to anything with no toolchain. - ·CI runs gofmt, vet, test -race, and govulncheck. That is the whole gate.
Remember: The module path is a URL, publishing is a git tag, and a breaking change means a new path with /v2 on the end.
Read the full topic →- ·Start with the standard library. It covers HTTP, SQL, JSON, logging, testing and crypto.
- ·
net/httproutes on method and path since 1.22, so a web framework is now a preference, not a need. - ·The few genuinely worth adding: a database driver,
errgroup,bcrypt, a JWT library, and metrics. - ·Judge a package by its last commit and what it drags in — not by its star count.
Remember: Every dependency is code you have to update, audit and explain for as long as you keep it. The stdlib rarely needs justifying.
Read the full topic →- ·Every file in one folder declares the same package name.
- ·Capitalised names are exported; lowercase ones are private to the package.
- ·The import path is the module path plus the folder.
- ·There is no
publicorprivatekeyword, and none is needed. - ·Once a module has many packages,
internal/folders and import cycles come into play: see Packages in code in the tooling section. - ·
net/httpandchishare the standard handler type; gin, echo and fiber each invent their own. - ·Database options in order of control:
database/sql→sqlx→sqlc→ent/GORM. - ·
require.NoErroris why teams adopt testify; the mocks and suites are the parts to think twice about. - ·Read
go.modandfunc mainfirst when opening an unfamiliar repo.
Remember: Capitalisation is not style. It is the access modifier. You are not learning every framework. You are learning to recognise which one a codebase uses, and what that choice locked in.
Read the full topic →Databases
- ·
*sql.DBis a pool. Create one, share it, always setSetMaxOpenConns. - ·Placeholders always.
fmt.Sprintfnear a query is a SQL injection. - ·
defer rows.Close(), check eachScan, and checkrows.Err()at the end. - ·Translate
sql.ErrNoRowsinto your own domain error at the repository boundary.
Remember: Learn SQL, not an ORM.
Read the full topic →database/sql shows you exactly which queries run, and that is a skill that outlives every library.- ·A query inside a loop is N+1. Fix it with a JOIN, or one batched
WHERE id = ANY($1). - ·A transaction is all-or-nothing. Use a named return so the deferred rollback sees the error.
- ·Transactions hold a connection: keep them short, and never call an external service inside one.
- ·
EXPLAIN ANALYZEevery query on a growing table. A sequential scan on a large table usually means a missing index.
Remember: The database is where your latency lives. One join beats twenty round trips, and one index beats a month of Go micro-optimisation.
Read the full topic →Practice projects
- ·A package is a folder; capitalisation decides what is visible outside it. A module is a project with a
go.mod. - ·Three layouts: flat for small things, grouped by layer (common but ages badly), grouped by domain for anything that grows.
- ·
cmd/holds runnable programs and no logic.internal/is private and the compiler enforces it. - ·Never make a
utilsorcommonpackage, and never let a package name stutter.
Remember: The layout should match the size of the problem. Start flat, move to one folder per feature when the flat version starts to hurt.
Read the full topic →- ·CRUD is Create, Read, Update, Delete: the four things almost every app does, repeated.
- ·A single file with one package is the right answer for something this size.
- ·A map plus a mutex is a store. Requests run in separate goroutines, so the lock is not optional.
- ·Pointer fields on an update tell "not sent" apart from "sent as empty".
Remember: Get the four operations right in one file before you add folders, packages or a database. Structure added too early hides whether the logic works.
Read the full topic →- ·Splitting into layers means each part has one job and can be tested without the others.
- ·
cmd/holds runnable programs.internal/is private and the compiler enforces that. - ·The storage layer never imports
net/http; the HTTP layer never importsdatabase/sql. - ·Translate driver errors like
sql.ErrNoRowsinto your own errors at the storage boundary.
Remember: A layer boundary is only real if the import rule holds. The moment your storage code imports
Read the full topic →net/http, the folders are decoration.- ·One folder per feature, with model, repository, service and handler inside it.
- ·A repository hides how data is stored. A service holds the rules. A handler only speaks HTTP.
- ·Dependencies point inward: handler → service → repository, never the reverse.
- ·Wire it by hand in
run() error. No framework, no globals, noinit().
Remember: The folders are not decoration. They are what stops your HTTP code and your SQL code from knowing about each other.
Read the full topic →Project 1 — URL shortener
- ·Write the endpoint table and the data table before any Go. It takes minutes and saves rewrites.
- ·The redirect lives at the root,
GET /{code}, so the short URLs stay short. - ·Build it in steps where the program runs after each one, not in one go.
- ·No accounts in this project. One thing at a time.
Remember: Decide what the API accepts and returns before you write code. A handler is easy to write and expensive to rewrite.
Read the full topic →- ·Get one route answering before you build anything else.
- ·
maincallsrun() errorand exits. There is oneos.Exit, outsiderun, so defers keep working. - ·Decide your JSON error shape once, in a helper, not in each handler.
- ·Set server timeouts from the start, not as a later fix.
Remember: A server you can curl is a foundation you can build on. Files written before anything runs are debt.
Read the full topic →- ·Build against memory first. A database is a step you take once the API already works.
- ·Keep the type and its errors in
model, and the code that stores it instore. - ·Every request runs in its own goroutine, so a shared map needs a lock.
- ·
RWMutexwhen reads heavily outnumber writes, which is the case here.
Remember: Talk to storage through a few named methods. That is what makes swapping memory for Postgres a one-file change later.
Read the full topic →- ·The service holds the rules and knows nothing about HTTP. That is what makes it testable.
- ·Use
crypto/randfor anything a stranger should not be able to guess. - ·
url.Parsesucceeding does not mean the URL is usable. Check the scheme and the host. - ·Cap the request body before decoding, and always
returnafter writing an error.
Remember: Every value coming from a client is untrusted: its size, its shape and its contents. Decide what you accept in one place, and reject everything else.
Read the full topic →- ·A redirect is a 3xx status plus a
Locationheader.http.Redirectwrites both. - ·Use 302, not 301. A cached 301 never reaches your server again, so you cannot count it or change it.
- ·Go 1.22 matches the most specific pattern, so
GET /linksbeatsGET /{code}. - ·Do the click count in the background, and do not give that goroutine the request context.
Remember: The redirect is the hot path. Everything the visitor does not need should happen after the response, not before it.
Read the full topic →- ·Building against an interface means changing storage touches the store package and
main.go, nothing else. - ·
sql.DBis a pool. Create one, share it, and always setSetMaxOpenConns. - ·Translate
sql.ErrNoRowsinto your ownErrNotFoundat the storage boundary. - ·Let the database do
clicks = clicks + 1, and let the UNIQUE constraint catch clashes.
Remember: Placeholders always. A query built by joining strings is a security bug waiting for the right input.
Read the full topic →- ·Paginate every list endpoint from the first version, and clamp the limit rather than rejecting it.
- ·Check
RowsAffectedso deleting nothing returns 404 instead of pretending it worked. - ·
srv.Shutdown(ctx)drains in-flight requests. Buffer the signal channel or you lose the signal. - ·
CGO_ENABLED=0plus a distroless base gives a ~15MB image with no shell or package manager for an attacker to use.
Remember: Finishing a project is pagination, shutdown, a test and a container. None of it is hard, and skipping it is what separates a demo from a service.
Read the full topic →Project 2 — Expense tracker
- ·Accounts exist to make one sentence true: I must never see your data.
- ·Authentication is who you are; authorisation is what you may do. Different questions.
- ·Every expense row stores a
user_id, and every query will use it. - ·Version the path (
/v1) from the first commit.
Remember: Login is not a feature you bolt on. It is the reason the data model has a
Read the full topic →user_id column in it at all.- ·Read config once at startup, check it, and refuse to start when something is missing.
- ·Store money as whole cents (the smallest currency unit) in an integer. Never a float.
- ·Let the database enforce what it can: foreign keys, cascades, unique and check constraints.
- ·Index the query you will actually run: here,
(user_id, spent_on DESC).
Remember: A rule the database enforces cannot be forgotten by a handler you write six months from now.
Read the full topic →- ·Hashing is one-way. You store the hash and compare hashes; you never read the password back.
- ·bcrypt is slow on purpose and salts for you. Never use SHA-256 or anything reversible for passwords.
- ·
json:"-"on the hash keeps it out of every JSON response without anyone having to remember. - ·Let the unique constraint decide, then translate error 23505. Check-then-insert is a race.
Remember: After
Read the full topic →Register returns, the plaintext password should exist nowhere: not in a variable you kept, not in a log, not in the response.- ·HTTP has no memory, so login hands back a token that later requests carry.
- ·A JWT payload is readable by anyone. The signature only proves it was not altered.
- ·Return the identical error and similar timing for a missing account and a wrong password.
- ·A JWT cannot be cancelled, so it is short-lived. Revoking is the refresh token’s job.
Remember: You never unhash a password. You hash the attempt and compare, which is why a stolen database leaves an attacker with slow, expensive guessing.
Read the full topic →- ·Check the token once, in middleware, so no handler can forget to.
- ·Always assert the signing method, so a token cannot choose how it is verified.
- ·Use an unexported struct type as the context key, and export a typed accessor.
- ·Wrap protected routes individually so nothing becomes public by accident.
Remember: Authentication happens once, at the edge. Everything downstream reads the user id from the context and never parses a token again.
Read the full topic →- ·Put ownership in the SQL:
WHERE id = $1 AND user_id = $2. Never a separate check in Go. - ·Return 404 for someone else’s row. A 403 confirms it exists.
- ·Make
userIDa required parameter of every repository method so it cannot be skipped. - ·Pointer fields in a PATCH request separate "not sent" from "sent as empty".
Remember: If the ownership check lives in Go, someone will eventually write a query that skips it. If it lives in the WHERE clause, they cannot.
Read the full topic →- ·Paginate from the first version, with a hard maximum, and clamp instead of rejecting.
- ·Build optional filters as fixed condition strings with the values in a separate args slice.
- ·Let the database aggregate.
GROUP BYandSUMbeat loading rows and looping. - ·A query inside a loop is N+1, one of the most common performance bugs there is.
Remember: Every list endpoint needs a ceiling, and every total belongs in the database. Both are much harder to add once people depend on your API.
Read the full topic →- ·Two tokens: a short JWT that does the work, and a long stored token that can be cancelled.
- ·Store the SHA-256 of the refresh token, never the token.
- ·Rotate on every refresh. Single use is what makes theft detectable.
- ·
crypto/randfor anything that must be unguessable.math/randthere is a vulnerability.
Remember: You cannot cancel a JWT. You cancel the refresh token and wait out the access token, which is why it is short.
Read the full topic →- ·Handlers with
httptest, services with a hand-written fake, repositories against a real database. - ·The cross-user 404 test is the most valuable test in the project. Write it first.
- ·
t.Helperandt.Cleanupdo the plumbing; you rarely need a mocking library. - ·Run
go test -racein CI, always.
Remember: A test against a fake repository only proves your fake works. The rules go against a fake; the SQL goes against a real database.
Read the full topic →Project 3 — Small shop
- ·Authentication is who you are (401). Authorisation is what you may do (403).
- ·A shop needs two things earlier projects did not: files on disk and money that cannot be lost.
- ·Use 404 instead of 403 when a 403 would confirm something exists.
- ·No real payments. The learning is in the transaction, not the card.
Remember: Roles are not a bigger login. They are a separate question asked after login has already been answered.
Read the full topic →- ·Let the database enforce stock, quantities and roles with CHECK constraints.
- ·Copy the price and name onto the order line, so history does not change when a product does.
- ·A
roletext column with a CHECK beats a boolean, because a third role costs one line. - ·Reuse the config, database, httpx, user and middleware packages you already built.
Remember: An order records what was true at the time it was placed. Anything it points at can change; anything it copies cannot.
Read the full topic →- ·Authentication and authorisation are separate middlewares, and the order matters.
- ·401 means we do not know you. 403 means we do, and the answer is no.
- ·A role in the token saves a query, at the cost of staying valid until the token expires. Write that trade down where the next developer will see it.
- ·Validate an upper bound on price, not just a lower one.
Remember: Knowing who somebody is tells you nothing about what they may do. Those are two questions and they deserve two checks.
Read the full topic →- ·
MaxBytesReaderbefore anything reads the body, thenParseMultipartFormwith the same limit. - ·Sniff the type with
http.DetectContentType. Never trust the extension or the client header. - ·Generate the stored filename with
crypto/rand. The client filename is display text only. - ·
io.Copystreams; if the database insert fails,os.Removethe file.
Remember: Every part of an upload is attacker-controlled: the size, the name, the type and the contents. Decide all four yourself.
Read the full topic →- ·
http.ServeFilehandles ranges and caching. Setnosniffso the browser believes your Content-Type. - ·Random, never-reused filenames mean images can be cached forever.
- ·
io.Readerandio.Writerhave one method each, which is why so much of the standard library composes. - ·Keep storage behind three methods so S3 later is a second implementation, not a refactor.
Remember: One-method interfaces are the reason files, sockets, buffers and HTTP bodies are interchangeable. It is one of the most useful design lessons in the standard library.
Read the full topic →- ·A cart is just rows scoped to a user. Nothing about it is special.
- ·
ON CONFLICT ... DO UPDATEdoes insert-or-increment in one statement, with no race. - ·One join beats fetching the cart then looping for each product. That loop is N+1.
- ·Do the arithmetic where the data is. Small set: Go. Large set: SQL.
Remember: A stock check when adding to a cart is a courtesy. The only check that counts is the one inside the checkout transaction.
Read the full topic →- ·A transaction makes several statements all-or-nothing. Checkout is the textbook case.
- ·Put the condition inside the UPDATE:
WHERE id = $2 AND stock >= $1, then checkRowsAffected. - ·Use a named return so the deferred rollback can see whether an error happened.
- ·Keep transactions short, never call an external service inside one, and lock rows in a consistent order.
Remember: Checking a value in Go and then changing it in SQL leaves a gap. Put the check in the WHERE clause and the gap disappears.
Read the full topic →- ·Orders are the same three rules again: scoped, paged, joined rather than looped.
- ·Structured logs with
slog: JSON in production, and never log secrets. - ·Rate-limit login and register hardest. That is where attacks land.
- ·
GOMEMLIMITandGOMAXPROCSin every container, and a volume for uploads.
Remember: Shipping is pagination, logging, limits, a container and one hardening pass. Each is small; together they are the difference between a demo and a service.
Read the full topic →Production
- ·One function maps domain errors to statuses. Handlers never choose a status themselves.
- ·Internal detail goes to the log with a request id; the client gets a generic message.
- ·
log/slogwith key–value pairs. JSON in production, text in development. - ·Liveness and readiness are different checks. Do not merge them.
Remember: The client gets a status and a safe message. You get the detail, the request id, and enough to find it in the logs.
Read the full topic →- ·Token-bucket rate limiting per IP, and a much tighter limit on the auth routes.
- ·CORS is an explicit allowlist, never
*on an authenticated API. SetVary: Origin. - ·
nosniff,DENY, and HSTS each close a whole class of attack in one line. - ·Never use
http.DefaultClient. Set a timeout, reuse one client, drain every body.
Remember: Rate limiting turns "an attacker gets unlimited guesses" into "an attacker gets twelve a minute". For a few dozen lines, few defences buy more.
Read the full topic →- ·Multi-stage build + distroless gives a ~15MB image with no shell and no package manager.
- ·
CGO_ENABLED=0is what makes both the static binary and cross-compiling work. - ·Set
GOMEMLIMITin every container, andGOMAXPROCStoo before Go 1.25. They prevent OOM kills and CPU throttling. - ·A Makefile with
checkgives you one command to run before every push.
Remember: Go’s deployment story is one static binary. Do not undo it by shipping a full OS image or letting the runtime guess your container limits.
Read the full topic →- ·Version the path now. Retrofitting
/v1after clients exist is painful. - ·A seed command and a
requests.httpfile save you time every time you reset the database. - ·The README is the run instructions plus the endpoint list. Nothing else is needed.
- ·Doc comments start with the identifier name and explain why, not what.
Remember: The project is finished when someone else can clone it and have it running in three commands.
Read the full topic →- ·gofmt, vet, race, govulncheck: all four clean before you review anything by hand.
- ·The eight-point sweep: auth, scope, SQL, errors, goroutines, logs, limits, paths.
- ·Attack your own API with curl. Six requests cover the most common holes.
- ·Delete something. Unused abstraction is the debt you are least likely to notice.
Remember: Reviewing your own code means reading it as if someone else wrote it and you have to maintain it. Be unkind to it now so production is kind to you later.
Read the full topic →- ·Profile before optimising. pprof on localhost only, never a public port.
- ·The database is where your latency lives. Micro-optimising Go is the last resort.
- ·Benchmark with
-count=10and benchstat, or you are reading noise. - ·fmt, vet, race, govulncheck before every push. Forever.
Remember: Correct, then clear, then fast, and only fast when a measurement told you to. An optimisation written without a profile often makes the code harder to read and no faster.
Read the full topic →Go comparisons
- ·Goroutines are run by the Go runtime; threads by the OS.
- ·Java virtual threads are the same idea; coroutines and async/await are cooperative and marked in the code.
- ·Goroutines start at 2 KB of stack and grow; threads reserve megabytes.
- ·The scheduler runs many goroutines on GOMAXPROCS threads (M:N, the GMP model).
- ·Goroutines are preemptive since Go 1.14, even in tight loops. "Cooperative" is outdated.
- ·There is no goroutine ID; pass data in arguments or a context.
Remember: Goroutines are cheap, runtime-scheduled, preemptive (since Go 1.14) and run on a few OS threads.
Read the full topic →- ·Mutex: guard shared state. Channel: move data or work between goroutines.
- ·Go wiki: use whichever is most expressive and/or most simple.
- ·Over-using channels is a known beginner mistake.
- ·"Share memory by communicating" is a design idea, not a ban on mutexes.
- ·Always test concurrent code with
-race.
Remember: State → mutex. Flow of data or work → channel. If both fit, pick the simpler one.
Read the full topic →- ·RWMutex: many readers or one writer. Mutex: one goroutine.
- ·A waiting writer blocks new readers, so writers do not starve, and a recursive
RLockcan deadlock. - ·RWMutex wins big when reads dominate and hold the lock long enough to overlap; with frequent writes a Mutex is faster. Benchmark it.
- ·There is no lock upgrade: unlock, lock, and check again.
- ·For one value, atomics; for a rarely replaced snapshot,
atomic.Pointerwith copy-on-write.
Remember: Default to Mutex. Earn RWMutex with a benchmark. Never RLock twice in one goroutine.
Read the full topic →- ·Array: fixed length, part of the type, copied on assign and pass.
- ·Slice: pointer + len + cap over an array; copies share elements.
- ·Arrays can be compared and used as map keys; slices cannot.
- ·
appendmay move a slice to a new array; always writes = append(s, x). - ·Use
s[a:b:b]to stop append overwriting the original.
Remember: Arrays are values with a fixed size. Slices are views that share memory. Use slices unless the size is truly fixed.
Read the full topic →- ·Unbuffered: a send waits for a receiver. It is a handshake.
- ·Buffered: sends go through until the buffer is full. It is a queue.
- ·Default to unbuffered; size a buffer only for a known reason.
- ·"all goroutines are asleep - deadlock!" usually means a missing receiver.
- ·A buffered channel of size n is a simple semaphore.
Remember: Unbuffered = both sides meet. Buffered = sender can run ahead by n values.
Read the full topic →- ·For coding rounds, pick the language you are fastest in and the platform allows.
- ·Java and C++ are the safest for online assessments; Python is the shortest.
- ·Go is fast and allowed on many platforms, but has fewer built-in structures.
- ·Go is a strong plus for backend, startup and infra roles.
- ·Check real job posts of your target companies; ignore made-up stats.
Remember: DSA in whatever you are fastest in. Go for backend projects that make your resume stand out.
Read the full topic →Interview preparation
- ·Give the short answer first, then stop unless they ask for more.
- ·Most Go interviews cover slices, maps, interfaces, errors and concurrency.
- ·Tricky output questions test defer order, slice sharing and the nil interface.
- ·For any question you miss, open the linked lesson and run its code.
Remember: Know the one-line answer for each question, and the lesson behind it for the follow-up.
Read the full topic →- ·At 3 years: correct concurrency and the language's sharp edges (slices, nil interfaces, defer, context).
- ·At 5 years: the runtime. Escape analysis, GC with GOGC and GOMEMLIMIT, the memory model, GMP, and pprof.
- ·At 8+ years: decisions. Package structure, module versioning, compatibility, incidents and code review.
- ·Every answer has a follow-up. Prepare the second sentence, not just the first.
- ·Bring two incident stories with a clear cause and a change that prevents a repeat.
Remember: Experienced Go interviews test what happens in production. Answer in two sentences, then be ready for "how would you find that?"
Read the full topic →- ·Lead with one sentence, then stop. Add the cost or the trap only if they want more.
- ·Zero values,
appendreturning, shared backing arrays, and method sets are the four most-asked mechanics. - ·The nil-interface trap comes up often. Know both why it happens and the one-line fix.
- ·Saying "do not add an interface until there is a second implementation" marks you as someone who has maintained Go.
Remember: They are testing whether you have written Go or read about it. Naming the cost of a design decision is what tells them apart.
Read the full topic →- ·Know the channel behaviour table cold, including why a nil channel blocking is useful.
- ·Be able to spot a goroutine leak and give two fixes in one sentence.
- ·A data race is undefined behaviour;
-racein CI is the answer to "how do you find one". - ·The worker pool is marked on:
Addbeforego, sender closes,ctx.Done()in every select, bounded concurrency.
Remember: Anyone can start a goroutine. The interview is about stopping one: how it exits, who waits for it, and what happens when it panics.
Read the full topic →- ·Structure the project answer: what → layout → one decision and its cost → one thing you would change.
- ·Owner scoping belongs in the SQL. That single line answers the whole security question.
- ·Slow endpoint: measure, then N+1, then indexes, then the pool. Go code is last.
- ·
GOMEMLIMITandGOMAXPROCSare the two answers to "it misbehaves in a container" (the second is automatic from Go 1.25, but only whengo.moddeclaresgo 1.25or later).
Remember: Every design answer is stronger when you name what it costs you. "I chose X, it cost me Y, and here is when I would switch" is the sentence they are listening for.
Read the full topic →- ·Restate the problem, ask about scale and input, and say the plan before typing.
- ·Errors,
ctx, and bounded concurrency are what actually get marked in a Go round. - ·Have the
errgroup.SetLimitfetch pattern memorised. It is one of the most common questions. - ·Narrate stuck moments. Silence scores worse than an imperfect answer.
Remember: They are not hiring the algorithm. They are hiring the person whose code the team will have to read.
Read the full topic →- ·Revise the nine mechanics above and nothing new the night before.
- ·"I do not know, but I would expect X because Y" beats a confident wrong answer.
- ·Have five questions ready — what you ask says as much as what you answer.
- ·Talk about your project concretely, with the costs of each decision.
Remember: They are deciding whether they want to read your code for the next two years. Clear beats clever, and honest beats confident.
Read the full topic →