Level: BeginnerGo Programs

Go Tricky Output Programs: Defer, Closures, Slices and nil

Updated 17 min read
Go Tricky Output Programs featured image: defer, slice and nil interface output

Go tricky output programs are short pieces of code where the printed result is not what most people expect. Interviewers love them because they show whether you really understand defer, closures, slices and interfaces. In this post, you will work through seventeen programs with their exact output, plus the logic explained in comments, so you can answer each one with confidence.

You should first finish our Go function programs, Go interface programs and Go generics programs. All programs were tested on Go 1.27.

What are Go Tricky Output Programs?

Go tricky output programs are small, complete programs that test one rule of the language. The code looks simple, but the answer depends on a detail, such as when a deferred call runs or whether two slices share memory.

Think of a magic trick. It looks impossible until someone shows you the hidden step. Each program here has one hidden step, and the comments show you where it is.

Why Go Tricky Output Programs Matter

These rules are not just interview puzzles. Each one is the cause of a real bug that teams find in production.

  • Defer bugs: a value is read too early or a return value changes unexpectedly.
  • Slice bugs: one slice quietly changes another.
  • Nil bugs: an error that looks nil is not nil.
  • Interviews: almost every Go round has at least one “what does this print?” question.

How to Solve Go Tricky Output Programs

Use the same three steps for every question. First, find the rule being tested. Next, trace the code line by line on paper, writing down each variable. Finally, write the output exactly, including spaces and new lines.

Go tricky output programs diagram showing defer calls running in last in first out order
Deferred calls are pushed onto a stack and run in reverse order when the function returns.

The table below lists the rules covered in this post.

TopicRule to remember
deferRuns last in, first out, and arguments are read at once
Named returnsA deferred function can change them
Loop variablesEach iteration has a new variable since Go 1.22
SlicesShare the array until append needs more space
Nil interfaceA typed nil pointer inside an interface is not nil
Stringslen counts bytes, range walks runes

Defer Go Tricky Output Programs

These first Go tricky output programs are all about defer, the most common topic in this kind of question. A defer line schedules a call to run when the current function ends.

Program 1: Order of Deferred Calls

package main

import "fmt"

func main() {
    defer fmt.Println("first")  // pushed first, so it runs last
    defer fmt.Println("second")
    defer fmt.Println("third")  // pushed last, so it runs first
    fmt.Println("main body")
}
main body
third
second
first

Deferred calls go onto a stack, like plates in a pile. First the normal line prints “main body”. When main returns, Go takes the calls off the top, so the last defer runs first.

Program 2: Defer Reads Arguments at Once

package main

import "fmt"

func main() {
    score := 1
    defer fmt.Println("deferred score:", score) // score is read NOW, so 1 is saved

    defer func() {
        fmt.Println("closure score:", score) // the closure reads score LATER, at the end
    }()

    score = 2
    fmt.Println("current score:", score)
}
current score: 2
closure score: 2
deferred score: 1

The trick is when score is read. A deferred call reads its arguments when the defer line runs, so it saved 1. A closure is different, because it reads the variable when it finally runs, and by then score is 2.

Program 3: Defer Changes a Named Return

package main

import "fmt"

// named has a named result: the defer can change result after return sets it.
func named() (result int) {
    defer func() {
        result = result * 2 // runs after "return 5" has set result to 5
    }()
    return 5 // sets result = 5, then the defer makes it 10
}

// plain has an unnamed result: return copies the value out before the defer runs.
func plain() int {
    result := 5
    defer func() {
        result = result * 2 // changes the local variable only
    }()
    return result // the value 5 is already copied out
}

func main() {
    fmt.Println(named(), plain())
}
10 5

With a named result, return 5 first stores 5 in result. Then the deferred call runs and doubles it to 10. With a plain result, the value 5 is already copied out, so the change is lost.

Program 4: Recover Inside a Deferred Function

package main

import "fmt"

// divide returns dividend / divisor, or an error instead of crashing.
func divide(dividend, divisor int) (result int, err error) {
    defer func() {
        problem := recover() // recover only works inside a deferred call
        if problem != nil {  // nil means there was no panic
            err = fmt.Errorf("recovered: %v", problem)
        }
    }()
    return dividend / divisor, nil // panics when divisor is 0
}

func main() {
    fmt.Println(divide(10, 2))
    fmt.Println(divide(1, 0))
}
5 <nil>
0 recovered: runtime error: integer divide by zero

Dividing by 0 causes a panic, which stops the function. Then the deferred call runs, catches the panic with recover and sets the named err. Because the panic happened before a value was returned, result keeps its zero value 0.

Closure and Loop Go Tricky Output Programs

Loops and closures were the source of a famous Go bug. Go 1.22 changed the rules, so these Go tricky output programs now give a friendlier answer.

Program 5: Closures Inside a Loop

package main

import "fmt"

func main() {
    var printers []func() // a slice of functions

    for i := 0; i < 3; i++ {
        // Since Go 1.22, each iteration has its own i,
        // so each closure keeps a different value.
        printers = append(printers, func() {
            fmt.Print(i, " ")
        })
    }

    for _, printNumber := range printers {
        printNumber() // call each saved function
    }
    fmt.Println()
}
0 1 2

The first loop saves three small functions, and each one remembers its own i. Before Go 1.22, all three closures shared one i, and the program printed 3 3 3. Now each iteration gets a fresh variable. The go line in your go.mod file decides which rule applies.

Program 6: Range over an Array Copies It

package main

import "fmt"

func main() {
    // Part 1: an array has a fixed size, written as [3]int.
    numbersArray := [3]int{1, 2, 3}
    for index, value := range numbersArray { // range loops over a COPY of the array
        if index == 0 {
            numbersArray[1] = 100 // change the original
            numbersArray[2] = 200
        }
        fmt.Print(value, " ")
    }
    fmt.Println(numbersArray)

    // Part 2: a slice, written as []int, is not copied. It shares the data.
    numbersSlice := []int{1, 2, 3}
    for index, value := range numbersSlice {
        if index == 0 {
            numbersSlice[1] = 100
            numbersSlice[2] = 200
        }
        fmt.Print(value, " ")
    }
    fmt.Println(numbersSlice)
}
1 2 3 [1 100 200]
1 100 200 [1 100 200]

Both loops change items 1 and 2 on the first pass. An array is a value, so range loops over a copy and still prints the old 2 and 3. A slice points to shared memory, so the second loop sees the new values.

Program 7: Shadowing with :=

package main

import "fmt"

func main() {
    size := 1
    if size := 2; size > 1 { // := makes a NEW size that lives only inside the if
        fmt.Println("inside:", size)
    }
    fmt.Println("outside:", size) // the outer size was never changed
}
inside: 2
outside: 1

:= always creates a new variable in the current block. So the size inside the if hides the outer one, and the outer one stays 1. This often hides an err by mistake, so read every := inside an if carefully.

Slice Go Tricky Output Programs

Slices are the topic people get wrong most often in Go tricky output programs.

Go tricky output programs diagram comparing append within capacity and append beyond capacity
Within capacity, append writes into the shared array. Beyond capacity, Go copies to a new array.

Program 8: Append Changes the Original Slice

package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    b := a[:2]        // b = [1 2], len 2, cap 4, same array as a
    b = append(b, 99) // there is room, so 99 is written into a[2]
    fmt.Println(a, b)
    fmt.Println(len(b), cap(b)) // len is the item count, cap is the room
}
[1 2 99 4] [1 2 99]
3 4

a[:2] takes the first two items, but b still uses the same array as a. Because b has spare capacity, append writes 99 into that shared array. That is why a[2] changed too.

Program 9: Append Beyond Capacity Makes a Copy

package main

import "fmt"

func main() {
    a := []int{1, 2, 3} // len 3, cap 3: no spare room
    b := append(a, 4)   // Go must allocate a new, larger array
    b[0] = 100          // only changes the new array
    fmt.Println(a, b)
}
[1 2 3] [100 2 3 4]

This time a is full, so append copies everything to a new array for b. After that, changing b[0] does not touch a. To be safe, never rely on which case happens, and use slices.Clone when you need a real copy.

Program 10: copy Uses the Shorter Length

package main

import "fmt"

func main() {
    destination := make([]int, 2)               // room for exactly 2 items
    copied := copy(destination, []int{1, 2, 3}) // copies only as many items as fit
    fmt.Println(copied, destination)

    var empty []int // a nil slice with length 0
    fmt.Println(copy(empty, []int{7, 8})) // nothing fits in a nil slice
}
2 [1 2]
0

copy never grows the destination. It copies min(len(dst), len(src)) items and returns that number. So only 2 items fit in the first case, and 0 fit in the empty slice.

Program 11: A Function Can Change Your Slice

package main

import "fmt"

// doublePrices doubles every price in the slice it receives.
func doublePrices(prices []int) {
    for i := range prices {
        prices[i] = prices[i] * 2 // writes into the caller's array
    }
}

// doubleNumber doubles a plain int, which is a copy.
func doubleNumber(number int) {
    number = number * 2 // changes only the copy
}

func main() {
    prices := []int{10, 20}
    doublePrices(prices)
    fmt.Println(prices)

    count := 5
    doubleNumber(count)
    fmt.Println(count)
}
[20 40]
5

Go passes every argument as a copy. But a slice copy still points to the same array, so doublePrices changes the caller’s prices. An int copy has no link back, so count stays 5.

Interface and Type Go Tricky Output Programs

Interfaces and basic types hide some of the hardest Go tricky output programs, because the rules live deep in the language spec.

Program 12: The Nil Interface Trap

package main

import "fmt"

// MyError is a custom error type.
type MyError struct{}

// Error makes *MyError satisfy the error interface.
func (*MyError) Error() string {
    return "my error"
}

// find returns a typed nil pointer wrapped in an error interface.
func find(found bool) error {
    var problem *MyError // problem is nil, but its type is *MyError
    if !found {
        problem = &MyError{}
    }
    return problem // the interface now holds (type=*MyError, value=nil)
}

// findFixed returns a real nil interface.
func findFixed(found bool) error {
    if !found {
        return &MyError{}
    }
    return nil // (type=nil, value=nil)
}

func main() {
    fmt.Println(find(true) == nil)
    fmt.Println(findFixed(true) == nil)
}
false
true

An interface is nil only when both its type and its value are nil. The first function returns a type with a nil value, so the check fails. Always return a plain nil for “no error”.

Program 13: Strings Count Bytes, Not Letters

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    word := "héllo" // é takes 2 bytes in UTF-8
    fmt.Println(len(word), word[1], utf8.RuneCountInString(word))

    for index, letter := range word { // range walks runes (letters), so index 2 is skipped
        fmt.Printf("%d:%c ", index, letter) // %c prints a rune as a letter
    }
    fmt.Println()
}
6 195 5
0:h 1:é 3:l 4:l 5:o

len counts bytes, so “héllo” has 6, not 5. Also word[1] is the first byte of “é”, which is 195. A range loop decodes whole runes instead, so the index jumps from 1 to 3.

Program 14: Integer Overflow and Division

package main

import "fmt"

func main() {
    var small int8 = 127 // int8 holds only -128 to 127
    small++              // 127 + 1 does not fit, so it wraps around
    fmt.Println(small)

    fmt.Println(7/2, -7/2, -7%3) // integer division drops the fraction
    fmt.Println(7.0 / 2)         // a float constant gives a float result
}
-128
3 -3 -1
3.5

Go integers wrap around silently at runtime, so 127 + 1 becomes -128. Integer division rounds towards zero, and the remainder takes the sign of the first number. Once one side is a float, you get 3.5.

Program 15: switch Does Not Fall Through

package main

import "fmt"

func main() {
    number := 2
    switch number {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
        fallthrough // runs the next case body without checking it
    case 3:
        fmt.Println("three")
    case 4:
        fmt.Println("four") // not reached: fallthrough moves only one step
    }
}
two
three

Go stops after the matching case by default, so you never need break. The fallthrough keyword runs only the very next case, without testing its condition. That is why “three” prints but “four” does not.

Program 16: fmt Prints a Map in Sorted Key Order

package main

import "fmt"

func main() {
    scores := map[string]int{"ravi": 2, "asha": 9, "meera": 5}

    // fmt sorts the keys before printing a map, so this is always the same.
    fmt.Println(scores)

    // A range loop over a map has NO fixed order, so we only count here.
    total := 0
    for _, score := range scores {
        total += score
    }
    fmt.Println("total:", total)
}
map[asha:9 meera:5 ravi:2]
total: 16

The trick is that two ways of reading a map behave differently. fmt.Println sorts the keys, so the printed map is always in a to z order. A range loop can visit keys in any order, so never print inside one if the order matters.

Program 17: Cannot Change a Struct Field Inside a Map

package main

import "fmt"

// Point is a position with one field.
type Point struct {
    X int
}

func main() {
    points := map[string]Point{"home": {X: 1}}
    points["home"].X = 5 // map values are not addressable, so this does not compile
    fmt.Println(points)
}
cannot assign to struct field points["home"].X in map

A map value is a copy, so Go refuses the change at compile time. Read the value, change it, then store it back with home := points["home"]; home.X = 5; points["home"] = home, or use map[string]*Point.

Go Tricky Output Programs vs Normal Bugs

Both look like “the code prints the wrong thing”, but they come from different places. The table below compares them.

FeatureTricky outputNormal bug
CauseA language rule you missedA logic mistake in your code
Found byKnowing the ruleTests and debugging
ExampleTyped nil in an interfaceWrong if condition
FixChange how you write the codeChange the logic
Prevent withgo vet, code reviewUnit tests

Common Mistakes in Go Tricky Output Programs

  • Thinking defer arguments are read late: they are read when the defer line runs.
  • Expecting 3 3 3 from loop closures: that was the old rule before Go 1.22.
  • Treating a sub-slice as a copy: it shares the array until append grows it.
  • Returning a typed nil pointer as an error: return plain nil instead.
  • Using len to count letters: use utf8.RuneCountInString.

Best Practices for Go Tricky Output Programs

  • Trace on paper and write down every variable after each line.
  • Write the output exactly, including spaces and blank lines.
  • Run go vet often, because it catches many of these traps.
  • Copy slices on purpose with slices.Clone when you need independent data.
  • Check the go.mod version, because loop rules depend on it.

Go Tricky Output Programs Interview Questions and Answers

These are the output questions interviewers ask most, and they build on the Go tricky output programs above. Each code answer is complete, with real output from Go 1.27.

Output Questions on Go Tricky Output Programs

Q1. What does defer inside a loop print?

package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        defer fmt.Print(i, " ") // i is read now: 0, then 1, then 2
    }
}
2 1 0

Each defer saves the current value of i, and the calls run in reverse order when main returns.

Q2. What happens when you write to a nil map?

package main

func main() {
    var ages map[string]int // nil map: reading is fine, writing is not
    ages["asha"] = 30
}
panic: assignment to entry in nil map

Create the map with make(map[string]int) or a literal before writing to it. Reading from a nil map simply returns the zero value.

Q3. What do you get from a closed channel?

package main

import "fmt"

func main() {
    numbers := make(chan int, 1) // a channel with room for one value
    numbers <- 5
    close(numbers)
    fmt.Println(<-numbers) // buffered values are still delivered

    value, ok := <-numbers // now empty and closed; ok is false
    fmt.Println(value, ok)
}
5
0 false

A closed channel still gives you any buffered values. After that, it returns the zero value and ok is false.

Q4. Does assigning an array copy it?

package main

import "fmt"

func main() {
    original := [2]int{1, 2}
    duplicate := original // arrays are values, so duplicate is a full copy
    duplicate[0] = 9
    fmt.Println(original, duplicate)
}
[1 2] [9 2]

Arrays are copied on assignment, so changing duplicate leaves original alone. A slice assignment would share the data instead.

Q5. Why does this method not change the struct?

package main

import "fmt"

// Counter keeps a count.
type Counter struct {
    count int
}

// Inc has a value receiver, so it works on a copy of the Counter.
func (counter Counter) Inc() {
    counter.count++
}

func main() {
    visits := Counter{}
    visits.Inc()
    fmt.Println(visits.count)
}
0

A value receiver gets a copy, so the change is thrown away. Use func (counter *Counter) Inc() to change the original.

Nil and Type Questions in Go Tricky Output Programs

Q6. What is the difference between a nil slice and an empty slice?

package main

import "fmt"

func main() {
    var nilSlice []int    // nil slice
    emptySlice := []int{} // empty, but not nil
    fmt.Println(nilSlice == nil, emptySlice == nil, len(nilSlice), len(emptySlice))
}
true false 0 0

Both have length 0 and both work with append and range. Only the nil slice is equal to nil, and JSON encodes it as null instead of [].

Q7. What does this iota block print?

package main

import "fmt"

const (
    Small  = iota // 0
    Medium        // 1
    _             // 2 is skipped
    Large         // 3
)

func main() {
    fmt.Println(Small, Medium, Large)
}
0 1 3

iota starts at 0 and adds 1 on each line of the const block. The blank identifier _ uses up a value without a name.

Q8. Are two interfaces holding 1 and 1.0 equal?

package main

import "fmt"

func main() {
    var whole any = 1     // type int
    var decimal any = 1.0 // type float64
    fmt.Println(whole == decimal)
}
false

Interface values are equal only when both the type and the value match. Here the types differ, so the answer is false.

Q9. What happens when main sends on an unbuffered channel with no receiver?

package main

func main() {
    numbers := make(chan int)
    numbers <- 1 // no goroutine is receiving, so main blocks forever
}
fatal error: all goroutines are asleep - deadlock!

An unbuffered send waits for a receiver. Go detects that no goroutine can ever run again and stops the program.

Concept Questions

Q10. What changed for loop variables in Go 1.22?

Each iteration of a for loop now creates a new variable. Closures and goroutines started inside the loop see the value from their own iteration, which removes the old i := i workaround.

Q11. When are deferred calls run if the function panics?

They still run. As the panic moves up the stack, every deferred call runs in reverse order, and one of them can call recover to stop the panic.

Q12. How do you prepare for tricky output questions?

Learn the six rules in the table at the top of this post, then practise Go tricky output programs by writing the output on paper before you run the code. Compare your answer with the real output and note any rule you missed.

Practice Task

To practise Go tricky output programs, predict the output of a function that returns a named err, defers a closure that wraps err with fmt.Errorf, and appends to a sub-slice of a slice passed in as an argument. Write your answer on paper first, then run it on the Go Playground and explain any difference.

Official Resources

Quick Recap

  • Go tricky output programs each test one hidden rule of the language.
  • Deferred calls run last in, first out, and their arguments are read at once.
  • A deferred closure can change a named return value.
  • Sub-slices share an array until append needs more room.
  • A typed nil pointer inside an interface is not equal to nil.

What’s Next?

You have finished Level 5 of the Go Programs series. Coming soon: Level 6, with data structure programs such as linked lists, stacks, queues and binary search. For more practice now, try the Go tricky output interview questions or revisit the Go mutex and worker pool programs.