Level: AdvancedInterview

Go Tricky Output Questions: Predict the Result (Part 27)

Updated 10 min read
Go Tricky Output Questions featured image: defer, append and typed nil cards

These Go tricky output questions ask you to predict what a short piece of code prints, then explain why. They cover constants, overflow, strings, slices, maps, defer, closures, interfaces, channels and errors. We gathered them from public interview lists and coding rounds, then rewrote each one in our own words.

This post is questions only, so answer first and run the code second. When you need help, read Go slices and arrays, Go panic and recover with defer and Go closures. Also, finish Part 26 on design first, since this part is pure revision.

How to Use These Go Tricky Output Questions

Read each of these Go tricky output questions, write your guess on paper, then run the snippet in a scratch file. The goal is not to memorise answers but to explain the rule behind each result. Finally, keep a list of the ones you got wrong and revisit them before every interview.

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

SectionWhat it testsQuestions
Types and constantsMath, overflow and iota15
Strings, slices and mapsBytes, runes, append and maps16
Functions and deferDefer order, closures and recover15
Structs and interfacesReceivers, embedding and nil15
Goroutines and channelsMain exit, select and closed channels15
Errors and builtinsWrapping, min, clear and copy13
Go Tricky Output Questions diagram showing six areas where Go output surprises people
The six areas where Go output most often surprises people in interviews.

Go Tricky Output Questions on Types and Constants

Before you answer, study Go variables, constants and data types and Go operators. These Go tricky output questions test integer math, overflow and untyped constants.

  1. What does fmt.Println(7 / 2, 7.0 / 2, 7 % -3) print, and why?
  2. Predict the output of fmt.Println(-7 / 2, -7 % 2).
  3. After var x uint8 = 255 and then x++, what is the value of x?
  4. Given const big = 1 << 62, what does fmt.Println(big >> 60) print?
  5. Why does a, b := 0.1, 0.2 followed by fmt.Println(a+b == 0.3) print false?
  6. Why does fmt.Println(0.1+0.2 == 0.3) print true when the line above prints false?
  7. What happens when you use iota outside a const block?
  8. In const ( A = iota * 10; B; C ), what are the values of B and C?
  9. In const ( X = iota; _; Y ), which value does Y get?
  10. What type does fmt.Printf(“%T”, ‘a’) print?
  11. Why does len(“héllo”) return 6 instead of 5?
  12. After x := 5 and then x, y := 6, 7 in the same scope, what is x, and why does it compile?
  13. What happens when you compile fmt.Println(math.MaxInt64 + 1)?
  14. Scenario: when a cart total of 0.1 plus 0.2 fails an equality test, what would you change in the code?
  15. Scenario: when a uint8 counter shows 0 after the 256th event, what happened, and how would you fix it?

Go Tricky Output Questions on Strings, Slices and Maps

Before you answer, study Go strings and Go maps. Shared arrays cause most surprises here, so these Go tricky output questions watch length and capacity closely.

  1. What happens when you write s := “go” and then s[0] = ‘G’?
  2. Predict the output of fmt.Println(string(rune(65)), string(byte(97))).
  3. Which index values does for i := range “héllo” produce?
  4. How many elements does strings.Split(“a,b,”, “,”) return, and what is the last one?
  5. After var s []int, what does fmt.Println(s == nil, len(s), s) print?
  6. Is s := []int{} equal to nil, and why does that matter for JSON?
  7. After a := [3]int{1, 2, 3}, b := a and b[0] = 9, what is a[0]?
  8. After s := []int{1, 2, 3}, t := s and t[0] = 9, what is s[0]?
  9. What does s := make([]int, 3) followed by s = append(s, 1) print?
  10. Given s := []int{1, 2, 3, 4, 5} and t := s[1:3], what are len(t) and cap(t)?
  11. How does the full slice expression s[1:3:3] change what a later append does?
  12. When you read m[“missing”] from a map[string]int, what value comes back?
  13. Can you write to a nil map, and what message appears if you try?
  14. Why does fmt.Println on a map show sorted keys, while a range loop does not?
  15. Scenario: when a function appends to its slice argument but the caller never sees the new item, what is happening?
  16. Scenario: when two slices taken from one array start changing each other, how would you separate them?

Go Tricky Output Questions on Functions and Defer

Before you answer, study Go functions and Go panic and recover with defer. Defer and closures look simple, yet these Go tricky output questions trip up many experienced developers.

  1. In what order do three defer statements in one function run?
  2. When does defer fmt.Println(x) read the value of x?
  3. If a deferred closure reads x and x changes after the defer line, which value prints?
  4. With a named result n, what does return 5 give when a deferred func runs n++?
  5. Does a deferred func that changes a local variable affect an unnamed return value?
  6. Before Go 1.22, what did three closures that print the loop variable i print, and what changed after?
  7. A closure increments a captured counter x that starts at 0, so what do three calls return?
  8. What does recover return when you call it directly instead of inside a deferred function?
  9. What happens to pending defers when main calls os.Exit(1)?
  10. Can you compare two function values with ==, and what does the compiler allow?
  11. Inside func f(args …int), what are len(args) and args == nil when you call f()?
  12. What happens when you call a function variable that is nil?
  13. If a deferred function panics while another panic is running, what does the crash report show?
  14. Scenario: when a loop with defer f.Close() runs out of file handles, what went wrong?
  15. Scenario: when a deferred log line prints an old value of a variable, how would you print the final value?

Go Tricky Output Questions on Structs and Interfaces

Before you answer, study Go interfaces and Go methods and receivers. These Go tricky output questions test copies, method sets and the typed nil trap.

  1. What does fmt.Println(struct{}{} == struct{}{}) print?
  2. What happens when you compare two structs that hold a slice field with ==?
  3. Why does p.Move() leave p unchanged when Move has a value receiver?
  4. Given var e error = (*MyErr)(nil), what does e == nil print?
  5. What does var i interface{} = nil followed by fmt.Println(i == nil) print?
  6. Why does fmt.Println(any(1) == any(1.0)) print false?
  7. When you compare two any values that both hold slices, what happens at run time?
  8. A struct embeds two types that both have a Name method, so what happens on s.Name()?
  9. If an outer struct defines String and also embeds a type with String, which one runs?
  10. Why does fmt skip a String method with a pointer receiver when you pass a value?
  11. Why does a String method that calls fmt.Sprintf(“%v”, t) on its own receiver overflow the stack?
  12. What happens when a struct holds a nil map field and you assign to it?
  13. How does %+v print a time.Duration that sits in an unexported field?
  14. Scenario: when a custom error check err != nil is true even on success, what would you look for?
  15. Scenario: when a log prints a pointer address instead of your String output, what is the likely cause?

Go Tricky Output Questions on Goroutines and Channels

Before you answer, study Go channels and Go select statement. Timing makes some of these results random, so explain which parts are certain.

  1. If main starts go fmt.Println(“hi”) and returns at once, what prints?
  2. What happens when main sends on an unbuffered channel that nobody reads?
  3. After close(ch) on an empty channel of int, what does v, ok := <-ch return?
  4. Can you close a channel twice, and what does the program print if you do?
  5. What does len(ch) return for a buffered channel that holds two items?
  6. When two select cases are ready, which one runs over many tries?
  7. What does a select with only a default case do?
  8. If nobody closes ch, what does for v := range ch do after the last value?
  9. What happens on a receive from a nil channel?
  10. Why can wg.Add inside the goroutine let Wait return too early?
  11. When one goroutine panics with no recover, what happens to the rest of the program?
  12. What does runtime.NumGoroutine usually print as the first line of main?
  13. Can a data race print a value that no goroutine ever wrote?
  14. Scenario: when a test passes alone but its output order changes with -count=10, what is the cause?
  15. Scenario: when a program prints fatal error: all goroutines are asleep, how would you find the stuck channel?

Errors and Built-in Functions

Before you answer, study Go error wrapping. These Go tricky output questions finish with errors and newer built-in functions.

  1. What does fmt.Println(errors.New(“x”) == errors.New(“x”)) print?
  2. Does errors.Is(fmt.Errorf(“wrap: %v”, io.EOF), io.EOF) return true?
  3. How does the answer change when the verb is %w instead of %v?
  4. Which case does a nil interface value match in a type switch?
  5. What does for i := range 3 print in Go 1.22 and later?
  6. What does min(3, 1, 2) return, and since which Go version?
  7. How does clear(m) affect a map, and how does clear(s) affect a slice?
  8. What does copy(dst, src) return when dst is shorter than src?
  9. Why does strings.TrimLeft(“aabbc”, “ab”) return a different result from strings.TrimPrefix(“aabbc”, “ab”)?
  10. What does fmt.Println(time.Duration(1500) * time.Millisecond) print?
  11. Why does fmt.Println(time.Duration(90) * time.Second) print 1m30s?
  12. Scenario: when a cleanup function trims too many characters from file names, which function did the code misuse?
  13. Scenario: when errors.Is fails after you add context to an error, what would you change?

Code Reading Questions

Read each program carefully and predict the output before you run it. Then explain the result in your own words.

package main

import "fmt"

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

func main() {
    for i := 0; i < 3; i++ {
        defer fmt.Print(i, " ")
    }
    x := 1
    defer fmt.Println("deferred x:", x)
    x = 10
    fmt.Println("count:", count())
}
  1. What does count return, and in which order do the deferred lines print?
  2. Why does the deferred line show x as 1 even though x becomes 10?

The second program mixes append, shared arrays and maps of slices.

package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    b := a[:2]
    b = append(b, 99)
    fmt.Println(a, b, len(b), cap(b))

    c := make([]int, 0, 2)
    c = append(c, 1, 2)
    d := append(c, 3)
    d[0] = 100
    fmt.Println(c, d)

    m := map[string][]int{}
    m["x"] = append(m["x"], 5)
    fmt.Println(len(m), m["x"], m["y"] == nil)
}
  1. Why does the append to b change a, but the change to d leaves c alone?
  2. What does the last line print, and why can you append to m[“x”] before the key exists?

Quick Revision Table for Tricky Rules

Use the table below as a final check before your interview. It lists the rules behind most tricky output questions.

RuleShort versionClassic trap
Integer divisionTruncates toward zero-7 / 2 is -3
Defer argumentsRead at the defer lineOld value prints
Defer orderLast in, first outReverse print order
Slice appendShares array if cap allowsChanges leak to the original
Typed nilInterface holds a typeerr != nil on success
Closed channelGives zero values foreverEndless loop without ok

Also, many interviewers ask what Go really copies on assignment. The diagram below shows the difference side by side.

Go tricky output diagram comparing copied values with shared values on assignment
Arrays, structs and numbers copy their data, while slices, maps and pointers share it.

Official Resources

These official pages explain the rules behind these questions.

Quick Recap

  • These Go tricky output questions cover constants, strings, slices, maps, defer, interfaces, channels and errors.
  • Integer division truncates, and unsigned numbers wrap around without a panic.
  • len on a string counts bytes, and range over a string walks runes.
  • Defer reads its arguments at once but runs the calls last in, first out.
  • An append can write into a shared array when capacity allows.
  • An interface that holds a nil pointer is not nil.

What’s Next?

By now, you have Go tricky output questions for every area that interviewers love to test. Study the rules in your own notes, then check them against the Go interview topics study guide.

Next up: Go difference between interview questions (Part 28)