Sobes.tech
Junior

What is defer in Go? What will the code output? How to make it output 4, 5, 6 instead of 1, 2, 3?

sobes.tech AI

Answer from AI

In Go, the keyword defer postpones the execution of a function until the surrounding function exits. All deferred calls are executed in reverse order (LIFO).

Example:

package main
import "fmt"

func main() {
    defer fmt.Println(3)
    defer fmt.Println(2)
    defer fmt.Println(1)
}

This code will output:

1
2
3

Because defer calls are executed in the reverse order of their declaration.

To output 4,5,6 instead of 1,2,3, you need to change the order of defer calls or avoid using defer and call functions directly:

package main
import "fmt"

func main() {
    fmt.Println(4)
    fmt.Println(5)
    fmt.Println(6)
}

Alternatively, if you want to use defer, declare them in reverse order:

package main
import "fmt"

func main() {
    defer fmt.Println(4)
    defer fmt.Println(5)
    defer fmt.Println(6)
}

This code will output:

6
5
4

To get exactly 4,5,6 with defer, you need to use additional functions or avoid using defer for this output.

What is defer in Go? What will the code output? How… - sobes.tech