educative.io

Quiz: Can you please explain Question 5 of Quiz

I am unable to understand how the output came for question 5? Can you please explain the concept?

Hi @Saurav_Kumar1 !!
In the given code:

package main
import "fmt"
func trace(s string) string {
    fmt.Println("entering:", s)
    return s
}
func un(s string) {
    fmt.Println("leaving:", s)
}
func a() {
    defer un(trace("a"))
    fmt.Println("in a")
}
func b() {
    defer un(trace("b"))
    fmt.Println("in b")
    a()
}
func main() {
    b()
}

We have a series of functions a, b, trace, and un, and we use defer statements to defer the execution of certain functions until the surrounding function returns.

Here’s the execution flow and the corresponding output of the program:

  1. We start from the main function and call b().

  2. Inside b(), we defer the un(trace("b")) statement. Since trace("b") is called first, it will print “entering: b” and return “b”.

  3. Then, we print “in b”.

  4. Next, b() calls a().

  5. Inside a(), we defer the un(trace("a")) statement. Similarly, trace("a") is called first, which prints “entering: a” and returns “a”.

  6. Then, we print “in a”.

  7. Now, we start unwinding the deferred calls. The deferred function un(trace("a")) inside a() is executed first, and it prints “leaving: a”. The trace("a") function was deferred and executed at the end of the a() function.

  8. Now, we are back in the b() function, and the deferred function un(trace("b")) is executed, printing “leaving: b”. The trace("b") function was deferred and executed at the end of the b() function.

So, the final output of the program will be:

entering: b
in b
entering: a
in a
leaving: a
leaving: b

The concept to understand here is that when a function is deferred using defer, its execution is postponed until the surrounding function returns. The deferred functions are executed in a Last In, First Out (LIFO) order, meaning the most recently deferred function will be executed first, and so on until the first deferred function is executed.
I hope it helps. Happy Learning :blush:

1 Like