Lesson 145 of 147 ยท Practice and Review
Go Interview Questions
49 common Go interview questions with answers: slices, maps, defer, interfaces, goroutines, channels, generics, the scheduler, garbage collection and memory.
Go interviews test two things: whether you know how the language really behaves (what a slice header contains, why a nil pointer inside an interface is not a nil interface, what happens when you send on a closed channel) and whether you can explain it plainly. This page collects 49 questions that come up again and again for backend, cloud and infrastructure roles, grouped by level and topic, with short, accurate answers you can expand in your own words.
Try to answer each question out loud before you open it. If you cannot explain an idea in two or three sentences, follow the link to its lesson and review it. Eight questions ask you to read code and predict the result: make your prediction first, then press Run.
Tip: a short correct answer with a tiny example beats a long recital. Mention the trap ("appending to a sub-slice can overwrite the original"), the safe habit ("I give the sub-slice a capacity limit with s[a:b:b]") and the tool that catches the bug ("go test -race finds data races"). That is what makes an answer sound like experience instead of memorization.
Junior level
Language basics
What is Go, and why do companies use it?
Go is a compiled, statically typed, garbage-collected language created at Google (first public release in 2009) for building servers and tools. It compiles very fast to a single static binary, has a small language that is easy to read in a team, ships a strong standard library (HTTP, JSON, testing, crypto) and makes concurrency cheap with goroutines and channels. It is widely used for cloud infrastructure (Docker, Kubernetes, Terraform), network services, APIs and command-line tools. See Getting Started with Go and Go Compared with Other Languages.
What is a zero value?
Every variable that is declared without an initial value is set to the zero value of its type: 0 for numbers, false for booleans, "" for strings and nil for pointers, slices, maps, channels, functions and interfaces. A struct's zero value has every field zeroed. Idiomatic Go designs types so that the zero value is useful: a sync.Mutex or a bytes.Buffer works without a constructor. There is no "uninitialized memory" in Go. See Variables and Zero Values.
What is the difference between var x = 1 and x := 1?
Both declare a variable with an inferred type. := is the short declaration: it is allowed only inside functions, needs at least one new variable on its left side, and can declare several variables at once (a, err := f()). var works at package level, can state a type without a value (var x int) and is the form to use when you want the zero value. A frequent bug is accidentally shadowing an outer variable with := inside an if or for block. See Variables.
What does "exported" mean in Go?
A name that starts with an upper-case letter (Println, Server, MaxSize) is exported: other packages can use it. A name that starts with a lower-case letter is visible only inside its own package. This rule applies to functions, types, variables, constants, struct fields and methods, and replaces keywords such as public and private. The package, not the type, is the unit of encapsulation. See Packages and Visibility.
Collections
What is the difference between an array and a slice?
An array has a fixed length that is part of its type ([3]int and [4]int are different types) and is a value: assigning or passing it copies all elements. A slice is a small descriptor with three fields, a pointer to an underlying array, a length and a capacity. Slices are cheap to pass around, grow with append, and several slices can share one array. In practice you almost always use slices. See Arrays and Slices.
What do len and cap mean for a slice?
len is the number of elements you can access (s[0] to s[len-1]). cap is the number of elements available in the underlying array starting from the slice's first element, so it is how far append can grow before it has to allocate a new array. make([]int, 3, 10) creates a slice with length 3 and capacity 10. Reslicing with s[:5] is allowed up to the capacity, not just the length. See How Slices Work.
How does a map behave when you read a missing key or write to a nil map?
Reading a missing key returns the value type's zero value, and the two-value form v, ok := m[k] tells you whether the key was present. Reading from a nil map is also fine. Writing to a nil map panics (assignment to entry in nil map), so create maps with make or a literal before storing. delete on a missing key does nothing. Iteration order is deliberately randomized, and a map must not be written by two goroutines at once. See Maps.
How do you loop over a map in sorted order?
Collect the keys, sort them, then index the map: for _, k := range slices.Sorted(maps.Keys(m)) { ... m[k] ... } (Go 1.23 and later). Before iterators existed you would append the keys to a slice and call sort.Strings. Never rely on the order of a plain range m: the runtime randomizes it so that programs do not depend on an accident. See The slices and maps Packages.
What is a rune, and how are strings represented?
A string is an immutable sequence of bytes, usually UTF-8 text. len(s) counts bytes, and s[i] is a byte. A rune is an alias for int32 and holds one Unicode code point. for i, r := range s decodes the string and gives byte offsets with runes, while []rune(s) converts to a slice of code points. To reverse or index by character, work with runes. See Strings, Bytes and Runes.
Functions, errors and pointers
How does error handling work in Go?
Functions that can fail return an error as their last result. The caller checks it immediately (if err != nil { return err }) and either handles it or adds context and returns it, for example fmt.Errorf("load config: %w", err). There are no exceptions for ordinary failures; panic is reserved for programmer mistakes and unrecoverable states. This makes the failure paths visible in the code. See Errors as Values and Error Handling Patterns.
What does defer do, and in what order do deferred calls run?
defer f(args) schedules a call to run when the surrounding function returns, whether normally, by return or by panic. The arguments are evaluated immediately, but the call happens later. Several deferred calls run in last-in, first-out order. Typical uses are closing files (defer f.Close()), unlocking mutexes and recovering from panics. Deferred closures can read and change the function's named results. See defer.
What is the difference between new and make?
new(T) allocates a zeroed value of type T and returns a pointer *T. make works only for slices, maps and channels and returns the initialized value itself (not a pointer), ready to use: make([]int, 0, 10), make(map[string]int), make(chan int, 4). In practice composite literals such as &Server{} are used far more often than new. See new, make and Composite Literals.
When do you use a pointer, and does Go have pointer arithmetic?
A pointer (*T, created with &x) lets a function or method change the caller's value, avoids copying a large struct and can express "no value" with nil. Go has no pointer arithmetic (outside the unsafe package), and the garbage collector keeps pointed-to data alive. Dereferencing a nil pointer panics. Small values such as ints and strings are usually passed by value. See Pointers and Pointers and Functions.
Concurrency basics
What is a goroutine?
A goroutine is a function running concurrently with others, started with go f(). It is much lighter than an OS thread (a few kilobytes of growable stack) and is scheduled by the Go runtime onto a small pool of threads, so programs can run hundreds of thousands of them. main does not wait for goroutines: when main returns the program ends, so you need a sync.WaitGroup or a channel to wait. See Goroutines.
What is the difference between an unbuffered and a buffered channel?
On an unbuffered channel (make(chan T)) a send blocks until another goroutine receives, so the two meet at that point: it synchronizes. A buffered channel (make(chan T, n)) has room for n values: a send blocks only when the buffer is full and a receive only when it is empty. Buffers decouple speed differences between producer and consumer, but they hide problems when they are used just to "make the deadlock go away". See Channels and Buffered Channels and select.
Mid level
Types and interfaces
What is the difference between value and pointer receivers?
A value receiver gets a copy of the value, so changes do not reach the caller; a pointer receiver gets the address and can modify the original and avoids copying large structs. Choose a pointer receiver if the method changes the receiver, if the type contains a sync.Mutex or similar that must not be copied, or if it is large, and then use pointer receivers for all methods of the type for consistency. This choice also decides which interfaces the type satisfies (see the next question). See Value vs Pointer Receivers.
What is a method set, and why can T fail to implement an interface that *T implements?
The method set of type T contains the methods declared with a value receiver. The method set of *T contains methods with both value and pointer receivers. If a method of the interface has a pointer receiver, only *T satisfies the interface, and assigning a plain T value is a compile error: T does not implement I (method M has pointer receiver). The reason is that a value stored inside an interface is not addressable, so the method could not modify it. See Value vs Pointer Receivers.
How do interfaces work in Go, and what does "accept interfaces, return structs" mean?
An interface is a set of method signatures. Any type with those methods satisfies it implicitly, with no implements keyword, so the consumer can define small interfaces for exactly what it needs (io.Reader has one method). "Accept interfaces, return structs" means: parameters should be as general as the function requires, while results should be concrete types so callers get all the details and the API can grow without breaking. Define interfaces where they are used, keep them small and do not create one before there are two implementations. See Designing with Interfaces.
What is the nil-interface trap?
An interface value holds a pair (dynamic type, dynamic value) and is nil only when both are nil. If a function returns a typed nil pointer as an error (var e *MyErr = nil; return e), the interface has type *MyErr and is not equal to nil, so if err != nil is true and the program reports a failure that never happened. The fix is to return the literal nil for success, and never return a concrete pointer type from a function that declares an interface result unless it is non-nil. See Interface Internals and the nil Trap.
What is the difference between a type assertion and a type switch?
A type assertion v, ok := x.(T) tests whether the interface value x holds a T (or, if T is an interface, implements it). Without the ok form it panics when the check fails. A type switch (switch v := x.(type) { case int: ... case string: ... }) tests several types in order and binds v with the right type in each case. Use them sparingly: needing many cases often means the interface should have a method instead. See Type Assertions and Type Switches.
Does Go have inheritance? What is embedding?
No. Go favors composition. A struct can embed another type by listing it without a field name; its fields and methods are then promoted to the outer type (e.Name instead of e.Person.Name), and the outer type satisfies the same interfaces. The outer type can override a promoted method by defining its own. The embedded type never knows about the outer type, so there is no virtual dispatch: a method of Person always sees a Person. See Struct Embedding and Composition.
Which types are comparable, and what can be a map key?
Booleans, numbers, strings, pointers, channels and interfaces are comparable, and so are arrays and structs whose elements or fields are all comparable. Slices, maps and functions are not comparable (only against nil) and cannot be map keys or used with ==. Comparing two interface values that hold the same uncomparable dynamic type panics at run time. Generic code uses the comparable constraint for types that support ==. See Constraints and Type Sets.
Slices, loops and the language
What happens when you append to a slice that shares an array with another slice?
If the slice has spare capacity, append writes into the shared array, which can overwrite elements that another slice still sees. If capacity is exhausted, append allocates a new, larger array, copies the elements and the two slices stop sharing. Because you cannot tell which happens just by reading the call, always use the returned slice (s = append(s, x)), and when you hand out a sub-slice, limit its capacity with a full slice expression (s[1:3:3]) or copy it. See How Slices Work.
What changed about loop variables in Go 1.22?
Before Go 1.22 a for loop had one variable shared by all iterations, so closures and goroutines created in the loop all saw its final value, a notorious bug. Since 1.22 each iteration gets its own copy of the variable (for variables declared with := in the loop header and for range loops), so go func() { use(i) }() captures what you expect. The new rule applies to modules whose go.mod declares go 1.22 or later. Go 1.22 also added for i := range 10. See for Loops and Closures.
How are init functions and package-level variables initialized?
Imported packages are initialized first (each package once, dependencies before dependents). Within a package, package-level variables are initialized in dependency order, then every init() function runs in the order the files are presented to the compiler (normally sorted by file name). A package may have several init functions and they cannot be called by hand. Only after all of that does main.main start. Avoid heavy work and hidden side effects in init; they make programs hard to test. See Packages and Visibility.
What are range-over-function iterators (Go 1.23)?
A for ... range loop can range over a function of type func(yield func(V) bool) (iter.Seq[V]) or func(yield func(K, V) bool) (iter.Seq2). The function calls yield for every value and stops when yield returns false, which happens when the loop body uses break or return. Iterators make lazy sequences, tree walks and custom collections usable with a plain for loop, and slices.Values, maps.Keys and slices.Collect build on them. See Iterators.
Errors
What is the difference between errors.Is and errors.As, and what does %w do?
fmt.Errorf("context: %w", err) wraps err: the new error prints the message but keeps the original inside, reachable through Unwrap. errors.Is(err, target) walks the chain and reports whether any error equals the target (a sentinel such as io.EOF). errors.As(err, &t) walks the chain looking for an error of a type and stores it in t so you can read its fields. Never compare wrapped errors with ==. errors.Join combines several errors. See Wrapping and Inspecting Errors.
When should you use panic and recover?
panic is for programmer errors and impossible states (an index out of range, a nil map write, a violated invariant at start-up), not for ordinary failures such as a missing file. A panic unwinds the stack running deferred calls; recover, called directly inside a deferred function, stops the unwinding and returns the panic value. Legitimate uses of recover are at boundaries: an HTTP server that must survive a bug in one handler, or a library that uses panic internally and converts it to an error before returning. See panic and recover.
Concurrency
How do sync.WaitGroup, Mutex, RWMutex and Once differ?
A WaitGroup waits for a group of goroutines to finish (wg.Go(f) since Go 1.25, or Add/Done/Wait). A Mutex gives exclusive access to shared data (Lock, then defer Unlock). An RWMutex allows many concurrent readers or one writer and pays off only when reads clearly dominate. Once runs a function exactly once, the usual tool for lazy initialization (sync.OnceFunc and OnceValue wrap it). None of them may be copied after first use. See The sync Package.
What is a data race, and how do you find one?
A data race happens when two goroutines access the same variable at the same time, at least one access is a write, and nothing orders them (no lock, channel or atomic). The result is undefined behavior: lost updates, torn values, crashes far from the cause. Prevent races by not sharing (send values through channels), by protecting shared data with a mutex, or by using sync/atomic. Detect them with the race detector: go test -race or go run -race. See Data Races and the Memory Model.
How does select work?
select waits on several channel operations and runs the case whose operation can proceed. If several are ready it picks one at random; if none is ready it blocks, or runs default when one exists. It is used for timeouts (case <-time.After(d)), cancellation (case <-ctx.Done()), non-blocking sends and receives, and for merging channels. A nil channel in a select is never ready, which is a handy way to disable a case. See Buffered Channels and select.
What happens when you send to, receive from or close a nil or closed channel?
Send on a nil channel blocks forever; send on a closed channel panics. Receive from a nil channel blocks forever; receive from a closed channel returns the zero value immediately (with ok == false in the two-value form) after any buffered values are drained. Closing a nil channel or an already closed channel panics. Only the sender should close, and only when receivers need to know that no more values come. See Channels.
What is a goroutine leak, and how do you prevent it?
A leak is a goroutine that can never finish, usually blocked forever on a channel send or receive that nobody will complete, or waiting on a lock or a WaitGroup. Leaked goroutines hold memory and whatever they reference. Prevent them by giving every goroutine an exit path: pass a context.Context and select on ctx.Done(), close channels when producers finish, use buffered channels for single results so a sender is never stuck, and test with testing/synctest or by counting goroutines. See Goroutines and Testing Concurrent Code.
What is context.Context for, and what are the rules for using it?
A context carries a cancellation signal, a deadline and request-scoped values across API boundaries and goroutines. Create one with WithCancel, WithTimeout or WithDeadline and always call the returned cancel function (usually with defer). Pass it as the first parameter named ctx, do not store it in a struct, never pass nil, and put only request-scoped data (a request ID, not optional function arguments) in values. Cancellation flows from parent to children, and ctx.Err() is context.Canceled or context.DeadlineExceeded. See The context Package.
Channels or mutexes: how do you choose?
Use channels to transfer ownership of data, to pass work between stages (pipelines, worker pools) and to signal events such as cancellation or completion. Use a mutex (or an atomic) to protect shared state that several goroutines read and update, such as a cache, a counter or a map. A channel-based design is not automatically better: a mutex around a map is simpler than a goroutine that owns the map and answers requests, unless that goroutine also coordinates other work. See Concurrency Patterns.
Generics, modules and tools
What are generics for in Go, and when should you avoid them?
Type parameters (Go 1.18) let one function or type work for many element types with compile-time safety: func Map[T, U any](s []T, f func(T) U) []U or a Stack[T]. Constraints such as comparable, cmp.Ordered or your own ~int | ~float64 say what operations are allowed. They fit algorithms and containers (slices, maps, sets, caches). Avoid them when an ordinary interface expresses the behavior (io.Reader), when only one type is ever used, or when they make the code harder to read. Methods cannot declare their own type parameters. See Generics in Practice.
How do Go modules and minimal version selection work?
A module is a tree of packages with a go.mod file that names the module path, the Go version and the required modules with versions. go.sum stores checksums of every dependency so downloads can be verified. When several dependencies need different versions of one module, Go picks the minimum version that satisfies everyone (minimal version selection) instead of the newest, which makes builds reproducible. go mod tidy adds missing and removes unused requirements. See Go Modules.
Senior level
Runtime and memory
How does the Go scheduler work?
The runtime multiplexes goroutines (G) onto OS threads (M) using logical processors (P); the number of Ps is GOMAXPROCS. A thread needs a P to run Go code. Each P has a local run queue of goroutines, there is a global queue, and an idle P steals half of the work of a busy one (work stealing). When a goroutine blocks in a system call the P is handed to another thread; network I/O goes through the netpoller, so thousands of goroutines can wait on sockets without tying up threads. Since Go 1.14 goroutines are preempted asynchronously, so a tight loop cannot starve others. See The Go Scheduler and Runtime Internals.
How do maps work internally, and why are they not safe for concurrent writes?
A map is a hash table: the key is hashed, the hash selects a slot, and the table grows when it becomes too full (Go 1.24 changed the implementation to Swiss tables, and earlier versions used buckets of eight entries with overflow chains). The hash seed and the iteration start are randomized per map. Writes modify internal structure (growth, moving entries), so unsynchronized concurrent writes would corrupt it; the runtime detects many cases and crashes with fatal error: concurrent map writes. Protect a map with a sync.Mutex or RWMutex; sync.Map suits only a few patterns (keys written once and read many times, or goroutines using disjoint keys). See Maps.
How does a slice grow, and how can a small slice keep a huge array alive?
append allocates a new array when capacity runs out. Small slices roughly double; larger ones grow more slowly (about 1.25 times plus a constant after a few hundred elements), and the result is rounded to a memory size class, so never assume an exact capacity. A sub-slice such as big[:10] still points into the large array, so keeping the small slice keeps all of the array alive. Copy the part you need (slices.Clone, copy) when the original is large and short-lived, and clear pointers in removed slots of a slice of pointers so the garbage collector can free them. See How Slices Work.
What is escape analysis, and how do you see its decisions?
The compiler decides at build time whether a variable can live on the goroutine's stack (cheap, freed automatically when the function returns) or must be allocated on the heap (garbage-collected) because it outlives the function: it is returned by address, stored in an interface or a global, captured by a closure that escapes, or its size is unknown. Allocation count matters because every heap allocation adds work for the garbage collector. Inspect the decisions with go build -gcflags=-m, and measure with benchmarks that report allocs/op. See Stack, Heap and Escape Analysis.
How does Go's garbage collector work, and what can you tune?
It is a concurrent, non-generational, non-moving mark-and-sweep collector using a tri-color algorithm and write barriers. Most of the marking runs alongside your program, with only short stop-the-world pauses. The main knobs are GOGC (the heap growth percentage that triggers a cycle, 100 by default) and GOMEMLIMIT (a soft total memory limit, since Go 1.19), which matters in containers. The best tuning is to allocate less: reuse buffers, preallocate slices, avoid needless pointers and boxing, and use sync.Pool for short-lived temporary objects. See Garbage Collection and Memory.
What does the Go memory model guarantee?
It defines when a read in one goroutine is guaranteed to see a write from another through a happens-before relation. Synchronization creates it: a send on a channel happens before the matching receive completes, closing a channel happens before a receive that sees the close, an Unlock happens before the next Lock, Once.Do completes before any call returns, and atomic operations are sequentially consistent. Without such ordering a program with a data race has no guarantees: the compiler and the CPU may reorder or cache accesses. The rule of thumb: if two goroutines touch the same data and one writes, synchronize. See Data Races and the Memory Model.
How are interfaces represented, and what do they cost?
A non-empty interface value is two words: a pointer to an itab (the dynamic type plus the table of methods for this interface) and a pointer to the data. The empty interface (any) holds a type pointer and a data pointer. Calling a method through an interface is an indirect call that usually cannot be inlined, and storing a non-pointer value in an interface can allocate (the compiler avoids this for small values and constants). That is rarely a problem, but in hot loops it can show up in a profile: prefer concrete types or generics there. See Interface Internals and the nil Trap.
How are struct fields laid out in memory, and why does field order matter?
Each field must be aligned to its own size (an int64 at an offset divisible by 8), and the compiler inserts padding to achieve it; the struct itself is padded to the alignment of its largest field. Ordering fields from the largest to the smallest usually removes the padding, so the same data takes less memory, which matters for millions of values and cache behavior. Check with unsafe.Sizeof and unsafe.Offsetof, or the fieldalignment analyzer. See Struct Memory Layout and Alignment.
Design and production
How do you shut down an HTTP server gracefully?
Run ListenAndServe in a goroutine, and wait for a signal with signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM). When it fires, call srv.Shutdown(ctx) with a timeout context: the server stops accepting new connections, waits for in-flight requests to finish, and returns; ListenAndServe then returns http.ErrServerClosed, which is not a failure. After that, stop background workers (cancel their context), flush logs and close databases. If the timeout expires, call srv.Close(). See Building an HTTP Server.
How do you limit concurrency, for example when calling an API for 10,000 items?
Never start 10,000 goroutines that hit one service. Use a worker pool (a fixed number of goroutines reading from a jobs channel), or a semaphore made of a buffered channel (sem <- struct{}{} before the work, <-sem after), or errgroup from golang.org/x/sync with SetLimit. Pass a context so the whole group stops on the first error or a timeout, collect results through a channel or by index, and make sure producers also stop when consumers quit, otherwise goroutines leak. See Concurrency Patterns.
How do you find and fix a performance problem in a Go service?
Measure first. Write a benchmark (testing.B, with b.Loop() since Go 1.24) and compare runs with benchstat. In a running service expose net/http/pprof, take a CPU, heap or goroutine profile and read it with go tool pprof (flame graphs show where the time goes); go tool trace shows scheduling and GC behavior. Typical wins are fewer allocations (preallocation, reusing buffers), better algorithms and data structures, batching I/O with bufio, and removing lock contention. Change one thing at a time and keep the benchmark. See Performance Tuning and Profiling and Debugging.
How would you structure and test a medium-sized Go service?
Keep packages small and named after what they provide, put the program entry points in cmd/<name>, hide implementation details in internal/, and wire dependencies explicitly in main (constructors that take interfaces) instead of using globals. Define interfaces at the consumer to allow fakes. Test with table-driven tests and subtests, use httptest for handlers, t.TempDir() for files, fuzz tests for parsers, and run go vet, a linter and go test -race ./... in CI. Layout is a convention, not a rule: start flat and split when a package gets hard to understand. See Project Layout and Table-Driven Tests.
Code-reading questions
Predict the result of each program before you run it.
What does this print? (defer)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
triple prints 9: the return n + 1 sets the named result n to 3, then the deferred closure multiplies it by 3 before the function really returns. In main, the line triple: 9 x: 20 comes first. Deferred calls run when main ends, last in, first out: x was 10 (the argument was evaluated when defer ran, before x = 20), then the loop's deferred prints with i equal to 2, 1 and 0. See defer.
What does this print? (slice aliasing)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
The first line is [1 2 3 100 5] [2 3 100] 3 4. b has length 2 and capacity 4, so append stores 100 in the shared array and overwrites a[3]. For c, the full slice expression a[1:3:3] limits the capacity to 2, so append allocates a new array and a is not touched: [1 2 3 100 5] [2 3 200] 3 true. See How Slices Work.
Is the error nil?
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
The first line is false true: mayFail(false) returns an error interface whose dynamic type is *MyError and whose value is a nil pointer, which is not a nil interface. The %T line confirms the type, and the nil pointer compares equal to (*MyError)(nil): *main.MyError true. mayFailCorrectly returns the literal nil, so the last line is true. Return nil explicitly on the success path. See Interface Internals and the nil Trap.
What does this print? (closures and loop variables)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
0 1 4, then [10 11 12], then 3. Since Go 1.22 every iteration of the first two loops has its own i, so the closures capture 0, 1 and 2 rather than a shared variable that ends at 3. The last loop does not declare its variable in the loop header (j was declared outside), so there is only one j, and show() sees its final value 3. See Anonymous Functions and Closures.
What happens here? (channels)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
The buffered values are still delivered after the channel is closed: 1 true, then 2 true. After they are drained, receives return the zero value at once with ok == false: 0 false 0 2. A receive from a nil channel would block forever, so in the select it is never chosen and default runs. Sending on the closed channel would have panicked. See Channels.
Does this compile? (fails on purpose)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
No, and the compiler lists every problem: "os" imported and not used, declared and not used: unused and missing return for sign. Go refuses unused imports and variables to keep programs tidy, and requires a function with results to end in a terminating statement. The if / else if chain has no final else, so the compiler cannot prove that every path returns; add a return 0 at the end. See Functions.
What happens here? (nil map, fails on purpose)
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
The reads work and print 0 0 true. The write panics: panic: assignment to entry in nil map, followed by goroutine 1 [running]: and the stack trace with the line of counts["go"]++. The program exits with status 2 and "unreachable" is never printed. Create the map with make(map[string]int) or a literal before writing. See Maps.
What size is this struct?
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Answer
Loose takes 24 bytes and Tight 16 (on a 64-bit platform). In Loose the bool is followed by 7 bytes of padding so ID starts at offset 8, and the last bool at offset 16 forces another 7 bytes of padding at the end. In Tight both booleans fit in the 8 bytes after ID, and the total is padded to a multiple of 8. See Struct Memory Layout and Alignment.
Summary
- Know the data structures behind the syntax: a slice is a header over a shared array, a map is an unordered hash table, a string is bytes, and an interface is a (type, value) pair.
- Explain errors as values,
%w,errors.Isanderrors.As, and keeppanicfor programmer mistakes and boundaries. - For concurrency, be ready to describe goroutines, channel rules,
select,sync,context, data races and leaks, and how you would limit and cancel work. - At senior level, connect the language to the runtime: the scheduler, escape analysis, the garbage collector, struct layout and profiling.
- Practice with the exercises, reread the cheat sheet, and build one of the projects so you have real stories to tell.
That is the end of the Go course. You now know the language, its standard library and the habits of Go programmers. The best next step is to build something of your own, read other people's Go code, and keep this page for your next interview. Good luck!
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of Go lessons completed