Go Interview Questions, Intermediate: Slices, Interfaces, Goroutines (30 questions)
30 intermediate Go (Golang) interview questions with model answers: slices and maps, methods and interfaces, errors, defer, goroutines, channels, select, context, generics and testing.
Take this exam on Brainbotox, with marking →
Question 1
Q1. Slices and append. What does this program print, and why? Then show how to make b independent of a.
a := []int{1, 2, 3, 4}
b := a[:2]
b = append(b, 99)
fmt.Println(a)
fmt.Println(b)
Model answer
It prints [1 2 99 4] then [1 2 99].
- A slice is a small header: a pointer to a backing array, a length and a capacity.
b := a[:2]has length 2 but capacity 4, and it points to the same array asa.appendhas room (2 < 4), so it does not allocate. It writes 99 into index 2 of the shared array, which isa[2].
Fixes
b := a[:2:2] // cap 2: append must copy
b := slices.Clone(a[:2]) // explicit copyThe three-index form a[low:high:max] limits the capacity, so the next append allocates a new array.
s = append(s, x), and why a function that appends to a slice it received can silently change the caller's data.Revise: Go Intermediate for Confirmed Developers
Question 2
Q2. The nil interface trap. What does this program print, and why? How do you fix do?
type MyErr struct{}
func (e *MyErr) Error() string { return "boom" }
func do() error {
var e *MyErr = nil
return e
}
func main() {
if err := do(); err != nil {
fmt.Println("error!")
} else {
fmt.Println("ok")
}
}
Model answer
It prints error!, although the pointer is nil.
- An interface value holds two things: a dynamic type and a value.
- An interface is
nilonly when both are nil. return econverts a nil*MyErrtoerror. The result has type*MyErrand value nil, so it is a non-nil interface holding a nil pointer.
Fix: return a literal nil on the success path, and never declare the result as a concrete error type.
func do() error {
var e *MyErr
if somethingFailed {
return e
}
return nil
}error interface, not *MyErr, and callers should inspect errors with errors.Is and errors.As.Revise: Go Intermediate for Confirmed Developers
Question 3
Q3. Goroutines. This program is meant to print 5050. Name the two bugs and write a correct version.
func main() {
total := 0
for i := 1; i <= 100; i++ {
go func() {
total += i
}()
}
fmt.Println(total)
}
Model answer
Bug 1: main does not wait. go starts the function and returns at once. main reaches Println and exits before most goroutines have run, so it prints 0 or some partial sum. When main returns, all goroutines are killed.
Bug 2: a data race. total += i is a read, an add and a write. A hundred goroutines do it on the same variable with no protection, so updates are lost.
Correct version
func main() {
var (
wg sync.WaitGroup
mu sync.Mutex
total int
)
for i := 1; i <= 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
total += i
mu.Unlock()
}()
}
wg.Wait()
fmt.Println(total) // 5050
}sync.WaitGroupmakesmainwait for every goroutine.sync.Mutexlets one goroutine at a time updatetotal.atomic.AddInt64would also work.
go run -race to detect the race. Before Go 1.22 there was a third bug: all closures shared one loop variable i. Since Go 1.22 each iteration has its own.Revise: Go Intermediate for Confirmed Developers
Question 4
Q4. Arrays and slices. What does this print, and what does it show about the difference between an array and a slice?
a := [3]int{1, 2, 3}
b := a
b[0] = 9
s := []int{1, 2, 3}
t := s
t[0] = 9
fmt.Println(a[0], s[0])
Model answer
It prints 1 9.
ais an array: a value of fixed size, and the size is part of its type ([3]int). Assigning it copies all the elements, so changingbleavesaalone.sis a slice: a small header (pointer, length, capacity) that refers to an underlying array. Assigning it copies only the header, sosandtshare the same elements.
In practice arrays are rare in Go code. Slices are the normal way to work with sequences.
Question 5
Q5. Nil and empty slices. What is the difference between var s []int and s := []int{}? Which operations behave the same, and where does the difference show?
Model answer
var s []intis a nil slice: no underlying array,s == nilis true.s := []int{}is an empty, non-nil slice.
Both have len 0 and cap 0, and both work with append, range and len. So test emptiness with len(s) == 0, not s == nil.
The difference shows when encoding:
json.Marshalof a nil slice givesnull;- of an empty slice gives
[].
Idiomatic Go declares slices with var s []T and lets append allocate, unless an API needs [].
Question 6
Q6. Maps. What happens on each of the three marked lines?
var m map[string]int
fmt.Println(m["a"]) // 1
m["a"] = 1 // 2
ages := map[string]int{"bob": 0}
v, ok := ages["amy"] // 3
Model answer
- Prints 0. Reading from a nil map is allowed and returns the zero value.
- Panics: assignment to entry in nil map. A map must be created with
make(map[string]int)or a literal before writing. vis 0 andokis false. The "comma ok" form tells a missing key apart from a key whose value is zero, such as"bob".
Also worth knowing:
- The iteration order of a map is deliberately random. Sort the keys if you need a stable order.
delete(m, key)is safe even if the key is absent.
Question 7
Q7. Maps and goroutines. Several goroutines read and write the same map. What happens, and what are two ways to make it safe?
Model answer
Maps are not safe for concurrent use. If one goroutine writes while another reads or writes, the runtime may detect it and crash the whole program with fatal error: concurrent map writes. This is not a panic and cannot be recovered.
Fix 1: a mutex (the usual choice).
type Cache struct {
mu sync.RWMutex
m map[string]string
}
func (c *Cache) Get(k string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.m[k]
return v, ok
}
func (c *Cache) Set(k, v string) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[k] = v
}Fix 2: sync.Map, built for two cases: keys written once and read many times, or goroutines working on disjoint sets of keys. For general use the mutex version is simpler and typed.
Question 8
Q8. Receivers. What does this print? Fix it, and explain when to use a pointer receiver.
type Counter struct{ n int }
func (c Counter) Inc() { c.n++ }
func main() {
c := Counter{}
c.Inc()
c.Inc()
fmt.Println(c.n)
}
Model answer
It prints 0. Inc has a value receiver, so it works on a copy of c. The copy is incremented and thrown away.
func (c *Counter) Inc() { c.n++ } // pointer receiverNow it prints 2. Go takes the address automatically: c.Inc() becomes (&c).Inc().
Use a pointer receiver when:
- the method must modify the receiver;
- the struct is large, to avoid copying it;
- the struct holds a
sync.Mutexor similar, which must not be copied.
Be consistent: if one method needs a pointer receiver, give all methods of the type pointer receivers.
Method sets: a value T has only the value-receiver methods, a *T has both. So if Inc is on *Counter, only *Counter satisfies an interface that requires Inc.
Question 9
Q9. Range copies. What does this print, and how do you fix the loop?
type P struct{ N int }
ps := []P{{1}, {2}, {3}}
for _, p := range ps {
p.N *= 10
}
fmt.Println(ps)
Model answer
It prints [{1} {2} {3}]. Nothing changed.
In for _, p := range ps, p is a copy of each element. The loop multiplies the copy.
Fix: modify the element through its index.
for i := range ps {
ps[i].N *= 10
}Or store pointers, []*P, so that p is a copy of the pointer and p.N reaches the real struct.
The same copy happens with arrays: range over an array copies the whole array first, so range over a slice of it or a pointer to it when it is large.
Question 10
Q10. defer order. What does this print, and why?
func main() {
for i := 0; i < 3; i++ {
defer fmt.Print(i)
}
fmt.Print("x")
}
Model answer
It prints x210.
- Deferred calls run when the surrounding function returns, not at the end of each loop iteration. So "x" is printed first.
- They run in last in, first out order: 2, then 1, then 0.
- The arguments of a deferred call are evaluated at the
deferstatement, so each call remembers its own value ofi.
Trap: defer inside a long loop (for example closing files) keeps every resource open until the function returns. Move the loop body into its own function so each defer runs per iteration.
Question 11
Q11. defer and named results. What does f() return, and why? Give one real use of this technique.
func f() (n int) {
defer func() {
n *= 2
}()
return 21
}
Model answer
It returns 42.
return 21first assigns 21 to the named resultn.- Then the deferred functions run. The closure can read and change
n, and doubles it. - Then the function really returns, with
nequal to 42.
Real use: reporting an error that happens during cleanup.
func write(path string, data []byte) (err error) {
f, err := os.Create(path)
if err != nil {
return err
}
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()
_, err = f.Write(data)
return err
}Without this, a failed Close (which can mean the data was not flushed) would be silently ignored.
Question 12
Q12. panic and recover. When should Go code panic, and when should it return an error? How does recover work?
Model answer
- Return an
errorfor anything that can reasonably happen: a missing file, bad input, a network failure. This is the normal path in Go. paniconly for programmer errors and impossible states: an index out of range, a nil dereference, a broken invariant, or a failure at start-up that makes the program pointless.
recover stops a panic and returns its value, but only when called directly inside a deferred function.
func safe(h func()) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
h()
return nil
}Typical use: an HTTP server recovers per request so one bad handler does not kill the process. A panic in a goroutine with no recover crashes the whole program, and one goroutine cannot recover another's panic.
Question 13
Q13. Wrapping errors. What is the difference between fmt.Errorf("load: %v", err) and fmt.Errorf("load: %w", err)? How do errors.Is and errors.As use it?
Model answer
%vonly copies the text. The original error is lost: callers can read the message but cannot test what kind of error it was.%wwraps the original error. The new error has the extra context and still gives access to the cause throughUnwrap.
err := fmt.Errorf("load config: %w", os.ErrNotExist)
errors.Is(err, os.ErrNotExist) // true: walks the chain
var pe *fs.PathError
if errors.As(err, &pe) { // finds a type in the chain
fmt.Println(pe.Path)
}errors.Is: is a specific error value anywhere in the chain?errors.As: is there an error of this type in the chain? If so, it is assigned to the target.
Do not compare with == or match on the message text: both break as soon as someone wraps the error.
Question 14
Q14. Type assertions. var v any = "hello". What happens on each line? Then write a type switch that handles int, string and everything else.
s := v.(string) // 1
n := v.(int) // 2
n, ok := v.(int) // 3
Model answer
sis"hello": the dynamic type isstring, so the assertion succeeds.- Panics: interface conversion, the value is a string, not an int.
- No panic:
nis 0 andokis false. Use this two-value form whenever the type is not certain.
func describe(v any) string {
switch x := v.(type) {
case int:
return fmt.Sprintf("int %d", x)
case string:
return "string " + x
case nil:
return "nil"
default:
return fmt.Sprintf("other %T", x)
}
}Inside each case, x already has that case's type. An interface in Go is satisfied implicitly: a type implements it by having the methods, with no implements keyword.
Question 15
Q15. Embedding. Go has no inheritance. What does embedding a struct do, and how is it different from inheritance?
type Logger struct{ prefix string }
func (l Logger) Log(msg string) { fmt.Println(l.prefix, msg) }
type Service struct {
Logger
name string
}
Model answer
Embedding promotes the fields and methods of the inner type to the outer type:
s := Service{Logger: Logger{"[svc]"}, name: "api"}
s.Log("started") // same as s.Logger.Log("started")It is composition with shorter syntax, not inheritance:
- A
Serviceis not aLogger. You cannot pass aServicewhere aLoggeris expected. - No virtual dispatch: inside
Log, the receiver is theLogger, which knows nothing aboutService. IfServicedefines its ownLog,Logger's other methods will not call it. - The outer type's own method with the same name hides the promoted one.
Useful consequence: promoted methods count for interfaces, so Service satisfies any interface that only requires Log(string). Polymorphism in Go comes from interfaces, code reuse from embedding.
Question 16
Q16. Strings, bytes and runes. What does this print, and why?
s := "héllo"
fmt.Println(len(s))
fmt.Println(len([]rune(s)))
for i, r := range s {
fmt.Print(i, ":", string(r), " ")
}
Model answer
It prints 6, then 5, then 0:h 1:é 3:l 4:l 5:o.
- A Go string is a read-only sequence of bytes, normally UTF-8 text.
len(s)counts bytes, andétakes 2 bytes. - A
runeis a Unicode code point (anint32). Converting to[]runedecodes the text: 5 characters. rangeover a string decodes one rune at a time and gives the byte index where it starts. That is why the index jumps from 1 to 3.
Consequences: s[1] is a single byte, not the letter é, and slicing with s[:2] can cut a character in half. To count characters use utf8.RuneCountInString(s).
Question 17
Q17. Shadowing. After setup() returns nil, the package variable db is still nil. Why? Fix it.
var db *DB
func setup() error {
db, err := Open("app.db")
if err != nil {
return err
}
db.Ping()
return nil
}
Model answer
:= declares new variables in the current scope. Inside setup, db, err := ... creates a local db that shadows the package-level one. The local is set, the global is never touched.
The compiler does not complain, because the local db is used.
func setup() error {
var err error
db, err = Open("app.db") // plain assignment
if err != nil {
return err
}
return db.Ping()
}The same bug appears with err inside an if or for block: the inner err is a new variable and the outer one stays nil. go vet with the shadow analyser, or a linter, finds these.
Rule: := reuses a variable only if it was declared in the same scope.
Question 18
Q18. Buffered and unbuffered channels. Explain the difference between make(chan int) and make(chan int, 3). What does this program do?
func main() {
ch := make(chan int)
ch <- 1
fmt.Println(<-ch)
}
Model answer
- Unbuffered (
make(chan int)): a send blocks until another goroutine receives, and a receive blocks until someone sends. The two goroutines meet: it is a synchronisation point. - Buffered (
make(chan int, 3)): a send blocks only when the buffer is full, a receive only when it is empty. Sender and receiver are decoupled, up to 3 values.
The program deadlocks. ch <- 1 waits for a receiver, but the only goroutine is main, which is stuck on that very line. The runtime reports: fatal error: all goroutines are asleep - deadlock!
Fixes: send from another goroutine (go func() { ch <- 1 }()), or give the channel a buffer of 1.
A buffer is not a fix for a design problem: choose its size for a reason, such as limiting work in progress.
Question 19
Q19. Closing channels. Say what happens in each case: (a) receiving from a closed channel, (b) sending on a closed channel, (c) closing a channel twice, (d) ranging over a channel. Who should close a channel?
Model answer
- (a) Receive from closed: never blocks. It returns the remaining buffered values, then the zero value for ever. Use
v, ok := <-ch:okis false once the channel is closed and empty. - (b) Send on closed: panic.
- (c) Close twice, or close a nil channel: panic.
- (d)
for v := range ch: receives until the channel is closed and drained, then the loop ends. If nobody closes it, the loop blocks for ever.
Who closes: the sender, and only the sender, because only it knows there is nothing more to send. With several senders, coordinate: for example a sync.WaitGroup for the senders and one goroutine that closes after wg.Wait().
Closing is a signal that no more values will come. It is not needed to free the channel: an unreferenced channel is garbage collected whether closed or not.
Question 20
Q20. select. What does select do? What happens when several cases are ready, and when none is? Write a receive with a 2 second timeout.
Model answer
select waits on several channel operations at once and runs one case that can proceed.
- Several ready: one is chosen at random, so no case can starve the others.
- None ready, no
default: it blocks until one is. - None ready, with
default: it runsdefaultat once. This gives a non-blocking send or receive.
select {
case v := <-results:
fmt.Println("got", v)
case <-time.After(2 * time.Second):
fmt.Println("timeout")
}In real code prefer a context, which the callee can also observe:
select {
case v := <-results:
use(v)
case <-ctx.Done():
return ctx.Err()
}An empty select {} blocks for ever.
Question 21
Q21. Nil channels. What happens when you send to or receive from a nil channel? Why is that useful inside a select?
Model answer
Sending to or receiving from a nil channel blocks for ever. It does not panic.
In a select, a case on a nil channel can never be chosen. So setting a channel variable to nil switches that case off.
func merge(a, b <-chan int, out chan<- int) {
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil // a is done: disable this case
continue
}
out <- v
case v, ok := <-b:
if !ok {
b = nil
continue
}
out <- v
}
}
close(out)
}Without this, a closed channel is always ready and returns zero values, so the loop would spin on the closed one.
Question 22
Q22. context. What is context.Context for? Explain what is wrong with this function and fix it.
func fetch(url string) (*http.Response, error) {
ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
return http.DefaultClient.Do(req)
}
Model answer
A Context carries cancellation, a deadline and request-scoped values down a call chain, so that when a request is cancelled or times out, all the work done for it can stop.
Problems:
- The cancel function is discarded. The timer and the context's resources stay alive until the timeout fires.
go vetreports this. - The function creates its own root with
context.Background(), so the caller cannot cancel it. - Errors from
NewRequestWithContextare ignored.
func fetch(ctx context.Context, url string) (*http.Response, error) {
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
return http.DefaultClient.Do(req)
}Conventions: ctx is the first parameter, it is passed down and not stored in a struct, and cancel is always called. Note that with defer cancel() here, the caller must read the body before the context is cancelled, so in real code the body is usually read inside this function.
Question 23
Q23. Worker pool. Write a function that processes a slice of jobs with exactly 4 goroutines and returns when all jobs are done.
Model answer
func processAll(jobs []Job) {
ch := make(chan Job)
var wg sync.WaitGroup
for w := 0; w < 4; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range ch { // ends when ch is closed
process(j)
}
}()
}
for _, j := range jobs {
ch <- j
}
close(ch) // tell the workers there is no more work
wg.Wait() // wait for them to finish
}- The channel hands each job to whichever worker is free.
close(ch)ends each worker'srangeloop. Forgetting it leaves the workers blocked for ever andwg.Wait()never returns.wg.Add(1)is called before starting the goroutine, not inside it.
Why limit to 4: to bound memory, CPU, open connections or load on a downstream service. To collect results or stop at the first error, use a results channel or errgroup.Group with SetLimit(4).
Question 24
Q24. sync.Once. Several goroutines call GetConfig() at the same time. Make sure the configuration is loaded exactly once.
var cfg *Config
func GetConfig() *Config {
if cfg == nil {
cfg = load()
}
return cfg
}
Model answer
The original is a data race: two goroutines can both see nil and both call load(), and reading cfg while another goroutine writes it is undefined.
var (
cfg *Config
once sync.Once
)
func GetConfig() *Config {
once.Do(func() {
cfg = load()
})
return cfg
}sync.Once guarantees that the function passed to Do runs exactly once, even with many concurrent callers. The others wait until it has finished, then all see the result.
Since Go 1.21 there is a shorter form:
var GetConfig = sync.OnceValue(func() *Config {
return load()
})Caveat: if load panics or fails, Once still counts as done and will not retry. Store and return the error if a retry matters.
Question 25
Q25. Generics. Write a generic function Map that applies a function to every element of a slice and returns the new slice. What is a constraint, and what do any and comparable mean?
Model answer
func Map[T, U any](in []T, f func(T) U) []U {
out := make([]U, 0, len(in))
for _, v := range in {
out = append(out, f(v))
}
return out
}
lengths := Map([]string{"go", "rust"}, func(s string) int {
return len(s)
}) // [2 4]T and U are type parameters. The compiler infers them from the arguments.
A constraint is an interface that says which types are allowed, and therefore what the code may do with them:
any: every type. You can only store, copy and pass the values.comparable: types that support==and!=, so they can be map keys.cmp.Ordered: types that support<and>(numbers and strings).
func Max[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}Use generics for containers and algorithms that work on many types. For behaviour, an ordinary interface is usually clearer.
Question 26
Q26. Modules. What are go.mod and go.sum? What do go mod tidy and a replace directive do?
Model answer
go.moddefines the module: its path (the import prefix), the Go version, and the required dependencies with their minimum versions.go.sumholds cryptographic checksums of each dependency's content. The go command checks downloads against it, so a dependency cannot change silently. Commit both files.go mod tidyadds requirements for packages the code imports and removes those no longer used.replacesubstitutes a module with another version or a local directory. Handy for testing a fix in a dependency. It applies only in the main module, so it is not inherited by projects that depend on yours.
Version selection is minimal version selection: Go uses the lowest version that satisfies every requirement, which makes builds reproducible without a separate lock file.
From major version 2, the major version is part of the import path: example.com/lib/v2.
Question 27
Q27. Table-driven tests. Write a table-driven test for func Abs(n int) int. Why is this style the Go standard?
Model answer
func TestAbs(t *testing.T) {
tests := []struct {
name string
in int
want int
}{
{"positive", 5, 5},
{"negative", -5, 5},
{"zero", 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Abs(tt.in); got != tt.want {
t.Errorf("Abs(%d) = %d, want %d", tt.in, got, tt.want)
}
})
}
}Why it is the standard:
- Adding a case is one line, so edge cases actually get tested.
- The logic is written once, so all cases are checked the same way.
t.Runmakes each case a named subtest: run one withgo test -run TestAbs/negative, and failures say which case broke.t.Errorfreports and continues, so one run shows every failing case.t.Fatalfstops that subtest.
Related tools: go test -race, -cover, benchmarks with func BenchmarkX(b *testing.B), and fuzzing with func FuzzX(f *testing.F).
Question 28
Q28. make and new. What is the difference between make and new? What do new([]int) and make([]int, 3) give you?
Model answer
new(T)allocates zeroed memory for aTand returns a pointer,*T. It works for any type.make(T, ...)works only for slices, maps and channels. It initialises their internal structure and returns a ready-to-useT, not a pointer.
new([]int)is a*[]intpointing to a nil slice. Rarely useful.make([]int, 3)is a[]intof length 3 containing zeros, backed by an allocated array.
For maps and channels the difference matters more: new(map[string]int) points to a nil map, and writing to it panics. make(map[string]int) is usable.
For structs, &T{...} is the idiomatic form and new(T) is seldom written.
Question 29
Q29. Comparable types. Which of these can be used as a map key: string, []int, [3]int, struct{ A int; B string }, struct{ A []int }, *T? State the rule.
Model answer
A map key must be comparable: usable with ==.
string: yes.[]int: no. Slices are not comparable (only tonil).[3]int: yes. An array is comparable when its element type is.struct{ A int; B string }: yes. A struct is comparable when all its fields are.struct{ A []int }: no, because of the slice field.*T: yes. Pointers compare by address, not by what they point to.
Not comparable: slices, maps and functions, and anything that contains them.
Struct keys are very useful for composite lookups: map[struct{ X, Y int }]Tile.
Trap: an interface is comparable at compile time, but comparing two interface values that hold a non-comparable type, such as a slice, panics at run time.
Question 30
Q30. Pass by value. What does this print, and why?
func modify(s []int) {
s[0] = 99
s = append(s, 4)
}
func main() {
s := []int{1, 2, 3}
modify(s)
fmt.Println(s, len(s))
}
Model answer
It prints [99 2 3] 3.
Go passes everything by value. The function receives a copy of the slice header (pointer, length, capacity), which points to the same underlying array.
s[0] = 99writes through the shared pointer, so the caller sees it.s = append(s, 4)changes the function's own copy of the header: a new length, and here a new array because the capacity was 3. The caller's header is untouched, so its length is still 3.
To let a function grow a slice, return the new slice:
func add(s []int) []int { return append(s, 4) }
s = add(s)The same reasoning applies to maps and channels, which are small handles to shared data: the callee can modify the contents, but reassigning the variable inside the function does not affect the caller.