0
0
Goprogramming~20 mins

Defer execution order in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Defer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Go program with multiple defers?

Consider the following Go code snippet. What will it print when run?

Go
package main
import "fmt"
func main() {
    defer fmt.Println("First")
    defer fmt.Println("Second")
    defer fmt.Println("Third")
    fmt.Println("Start")
}
A
Start
First
Second
Third
B
Third
Second
First
Start
C
Start
Second
Third
First
D
Start
Third
Second
First
Attempts:
2 left
💡 Hint

Remember that deferred functions are executed in last-in, first-out order after the surrounding function returns.

Predict Output
intermediate
2:00remaining
What is the output when defers modify a variable?

What will this Go program print?

Go
package main
import "fmt"
func main() {
    x := 0
    defer fmt.Println(x)
    x = 5
    defer fmt.Println(x)
    x = 10
}
A
5
10
B
0
5
C
5
0
D
5
5
Attempts:
2 left
💡 Hint

Deferred function arguments are evaluated when the defer statement executes, not when the function runs.

Predict Output
advanced
2:00remaining
What is the output of this Go program with deferred anonymous functions?

Analyze this code and select the correct output.

Go
package main
import "fmt"
func main() {
    x := 1
    defer func() { fmt.Println(x) }()
    x = 2
    defer func(x int) { fmt.Println(x) }(x)
    x = 3
}
A
2
3
B
3
2
C
3
3
D
1
2
Attempts:
2 left
💡 Hint

Deferred anonymous functions without parameters capture variables by reference; those with parameters capture by value.

Predict Output
advanced
2:00remaining
What error or output does this Go code produce?

What happens when you run this Go program?

Go
package main
import "fmt"
func main() {
    defer fmt.Println("A")
    defer fmt.Println("B")
    panic("error")
    defer fmt.Println("C")
}
A
B
A
panic: error
B
A
B
panic: error
Cpanic: error
D
C
B
A
panic: error
Attempts:
2 left
💡 Hint

Deferred functions run even if a panic occurs, but only those deferred before the panic.

Predict Output
expert
3:00remaining
What is the final value of x after this Go function runs?

Consider this Go function. What is the value of x printed at the end?

Go
package main
import "fmt"
func main() {
    x := 0
    defer func() {
        x += 1
        fmt.Println("defer1:", x)
    }()
    defer func() {
        x += 2
        fmt.Println("defer2:", x)
    }()
    x = 5
    fmt.Println("main:", x)
}
A
main: 5
defer1: 1
defer2: 3
B
main: 5
defer2: 7
defer1: 8
C
main: 0
defer2: 2
defer1: 3
D
main: 5
defer2: 3
defer1: 4
Attempts:
2 left
💡 Hint

Deferred functions run in reverse order and modify the same variable x.