DEV Community

Cover image for How to postpone or defer an inner function call until the outer or surrounding function completes its execution in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to postpone or defer an inner function call until the outer or surrounding function completes its execution in Go or Golang?

#go

Originally posted here!

To postpone or defer an inner function's execution until the outer or surrounding function execution completes, you can use the defer keyword followed by the function call in Go or Golang.

TL;DR

package main

import "fmt"

// function that prints string to the terminal
func sayBye(){
    fmt.Println("Bye, Have a nice day!")
}

func main(){
    // postpone or defer the `sayBye()` function call until the
    // `main()` function execution completes
    defer sayBye()

    fmt.Println("I will be executed first")
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a function called sayBye() which prints Bye, Have a nice day! to the user only after the main function execution completes.

To do that first let's make the sayBye() function that prints the string Bye, Have a nice day! to the console or terminal like this,

package main

import "fmt"

// function that prints string to the terminal
func sayBye(){
    fmt.Println("Bye, Have a nice day!")
}
Enter fullscreen mode Exit fullscreen mode

Now at the top of the main() function, we can use the defer keyword followed by the sayBye() function call like this,

package main

import "fmt"

// function that prints string to the terminal
func sayBye(){
    fmt.Println("Bye, Have a nice day!")
}

func main(){
    // postpone or defer the `sayBye()` function call until the
    // `main()` function execution completes
    defer sayBye()
}
Enter fullscreen mode Exit fullscreen mode

Since we don't have many lines of code to see the working correctly, let's add another Println() function to show the string of I will be executed first after the defer statement like this,

package main

import "fmt"

// function that prints string to the terminal
func sayBye(){
    fmt.Println("Bye, Have a nice day!")
}

func main(){
    // postpone or defer the `sayBye()` function call until the
    // `main()` function execution completes
    defer sayBye()

    fmt.Println("I will be executed first")
}
Enter fullscreen mode Exit fullscreen mode

The output of running the above code will look like this,

I will be executed first
Bye, Have a nice day!
Enter fullscreen mode Exit fullscreen mode

As you can see that the I will be executed first string is shown before the string Bye, Have a nice day! even though it is evaluated first.

We have successfully postponed or deferred the function call. Yay 🥳.

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)