Level: BeginnerInterview

Go Functions Interview Questions: Closures, Defer (Part 4)

Updated 9 min read
Go Functions Interview Questions featured image: variadic, defer and closure cards

These Go functions interview questions cover declarations, multiple returns, variadic functions, closures, defer and function types. We gathered them from public interview lists, coding tests and community threads. Then we grouped them by idea, so you can revise one part at a time.

This post is questions only, so answer each one in your own words first. When you need a refresher, read Go functions for beginners and Go closures. Also keep Go defer, panic and recover open. Also, finish Part 3 on control flow first.

How to Use These Go Functions Interview Questions

Answer each question out loud in two or three sentences. Then write a small program for every defer and closure question, because these topics hide surprises. Finally, try the scenario questions, since they test design and not only syntax.

The table below lists each section and its number of questions.

SectionWhat it testsQuestions
BasicsDeclaring and calling functions15
Returns and errorsMultiple and named results14
Variadic functionsUsing … in parameters and calls11
ClosuresAnonymous functions and captured values15
deferOrder, arguments and named results16
Function typesFunctions as values and callbacks15
Code readingPredict the output4
Go Functions Interview Questions diagram showing six question areas from basics to function types
Go functions interview questions grouped into six areas: basics, returns and errors, variadic functions, closures, defer and function types.

Go Functions Interview Questions on the Basics

Before you answer, study Go functions for beginners. These Go functions interview questions check that you know the syntax well.

  1. How do you declare a function in Go, and where does the return type go?
  2. Why can you write func add(a, b int) int instead of repeating int?
  3. Does Go pass arguments by value or by reference?
  4. If Go passes by value, why can a function change the elements of a slice?
  5. Why can a function not change a map variable itself, even though it can change the map entries?
  6. When should a parameter be a pointer instead of a value?
  7. Does Go support function overloading, so how do you handle different inputs?
  8. Does Go support default parameter values, and what do teams use instead?
  9. What is a function signature, and when are two signatures the same?
  10. Can a function be declared inside another function?
  11. What is the difference between a function and a method?
  12. Why are exported function names written with a capital letter?
  13. How does recursion work in Go, and is there tail call optimisation?
  14. Scenario: when a function takes eight parameters, how would you make it easier to call?
  15. Scenario: when a function changes a large struct by value and nothing happens, what is the bug?

Go Functions Interview Questions on Returns and Errors

Go functions often return two values. So Go functions interview questions about this pattern appear in almost every round.

  1. How do you return more than one value from a function?
  2. Why does Go return an error as the last value instead of throwing an exception?
  3. What are named return values, and when do they help?
  4. What is a naked return, and why do many teams avoid it?
  5. How do you ignore one of the returned values?
  6. What should a function return for the other values when it returns an error?
  7. Can you pass the results of one function directly into another function?
  8. How do you return a function from a function?
  9. Why should you not return a typed nil pointer as an error interface?
  10. How would you return a result and a boolean, such as the comma ok idiom?
  11. When is it better to return a struct than four separate values?
  12. How do named results interact with defer?
  13. Scenario: when a caller keeps forgetting to check an error, how would you change the API?
  14. Scenario: when an error from a helper loses its context in logs, how would you wrap it?

Go Functions Interview Questions on Variadic Functions

Variadic functions accept any number of values. So these Go functions interview questions check both the declaration and the call.

  1. What is a variadic function, and how do you declare one?
  2. What type does a variadic parameter have inside the function?
  3. Why must the variadic parameter be the last parameter?
  4. How do you pass a slice to a variadic function?
  5. What happens when you call a variadic function with no arguments?
  6. Can the function change the caller’s slice when you pass it with …?
  7. Which standard library functions are variadic, such as fmt.Println and append?
  8. How is ...any used, for example in a logging helper?
  9. When would a slice parameter be clearer than a variadic one?
  10. Scenario: when a helper must accept one or more user IDs, which signature would you choose?
  11. Scenario: when a variadic options list keeps growing, which pattern would you move to?

Closures and Anonymous Functions Questions

Before you answer, study Go closures and anonymous functions. Closures are a favourite topic, because many bugs hide there.

  1. What is an anonymous function, and how do you call it right away?
  2. What is a closure, and what does it capture?
  3. Does a closure capture a copy of a variable or the variable itself?
  4. How would you build a counter function with a closure?
  5. Do two counters made by the same factory share their state?
  6. Where does a captured variable live, on the stack or the heap?
  7. What was the classic loop closure bug before Go 1.22?
  8. How did Go 1.22 change closures that capture loop variables?
  9. How do closures help with middleware in a web server?
  10. Can a closure change a variable from the outer function?
  11. When can a closure cause a memory leak?
  12. How do you pass extra data to a callback without changing its signature?
  13. Why are closures useful with sort.Slice?
  14. Scenario: when goroutines started in a loop all print the same value in old code, how would you fix it?
  15. Scenario: when a cache closure keeps growing in memory, what would you check?

Go Functions Interview Questions on defer

Before you answer, study Go defer, panic and recover. These Go functions interview questions often come with code to read.

  1. What does defer do, and when does the deferred call run?
  2. In what order do several deferred calls run?
  3. When are the arguments of a deferred call evaluated?
  4. Can a deferred function change a named return value?
  5. Why is defer often used right after opening a file?
  6. What happens to deferred calls when a function panics?
  7. How does recover work, and why must it be inside a deferred function?
  8. What is the cost of defer, and did it improve in newer Go versions?
  9. Why can defer inside a loop be a problem?
  10. How do you handle the error returned by a deferred Close call?
  11. Does defer run when you call os.Exit?
  12. Can you defer a method call on a nil pointer?
  13. How does defer help you release a mutex lock safely?
  14. What is the difference between defer f() and defer func() { f() }()?
  15. Scenario: when a loop opens 10,000 files with defer and runs out of handles, how would you fix it?
  16. Scenario: when a panic in one request crashes the whole server, where would you add recover?

Function Types and Higher Order Functions Questions

Functions are values in Go. So you can store them, pass them and return them like any other value. These last Go functions interview questions test that idea.

  1. What does “functions are first class values” mean in Go?
  2. How do you declare a function type, such as type Handler func(string) error?
  3. Can you compare two function values with ==?
  4. What is the zero value of a function variable, and what happens if you call it?
  5. What is a higher order function, and can you give an example?
  6. How would you write a map or filter function with generics?
  7. When is a function type better than an interface with one method?
  8. How does http.HandlerFunc turn a function into a handler?
  9. What is a callback, and how is it used in Go?
  10. How do you store functions in a map, for example for commands?
  11. What is a method value, such as f := c.Inc?
  12. What is a method expression, and how is it different from a method value?
  13. How can the functional options pattern use function types?
  14. Scenario: when a CLI has 20 commands in one switch, how would a map of functions help?
  15. Scenario: when tests need a fake clock, how would a function field make it easy?

Code Reading Questions

Read each program and predict the output before you run it. Then explain your answer in plain words.

package main

import "fmt"

func count() (n int) {
	defer func() { n *= 2 }()
	n = 5
	return n + 1
}

func main() {
	for i := 0; i < 3; i++ {
		defer fmt.Println("deferred", i)
	}
	fmt.Println("result:", count())
}
  1. What does this program print, and in which order?
  2. Why is the result not 6, even though the function returns n + 1?

Here is the second program. This time, focus on closures and variadic calls.

package main

import "fmt"

func counter() func() int {
	n := 0
	return func() int {
		n++
		return n
	}
}

func sum(nums ...int) int {
	total := 0
	for _, v := range nums {
		total += v
	}
	return total
}

func main() {
	a, b := counter(), counter()
	fmt.Println(a(), a(), b())

	list := []int{1, 2, 3}
	fmt.Println(sum(), sum(list...))
}
  1. What does the first Println show, and why do a and b not share a count?
  2. What does sum return with no arguments, and what does list... do?

Quick Revision Table for defer

Many tricky questions depend on the rules of defer. So use the table below as a final check.

RuleWhat happens
OrderLast in, first out
ArgumentsEvaluated when defer runs, not later
Named resultsA deferred function can change them
PanicDeferred calls still run
os.ExitDeferred calls do not run

Also, remember the difference between a plain function and a closure. The diagram below compares them.

Go Functions Interview Questions diagram showing a comparison of a plain function and a closure
A plain function only uses its parameters and globals, while a closure also keeps the variables it captured, so its state survives between calls.

Official Resources

These official pages explain the rules behind these questions.

Quick Recap

  • These Go functions interview questions cover basics, returns, variadic functions, closures, defer and function types.
  • Go passes everything by value, even slices and maps headers.
  • Deferred calls run last in, first out, and their arguments are evaluated early.
  • A closure captures variables, not copies of their values.
  • Functions are values, so you can store, pass and return them.
  • Run the code reading programs to check your answers.

What’s Next?

By now, you have Go functions interview questions for every part of the functions round. So next, we will cover arrays, slices and maps, which bring the most tricky questions of all.

Next up: Go slice interview questions on arrays, slices and maps (Part 5)