More about Golang Functions—Defer

In this class, we follow up our discussions on functions by looking at the special statement “defer” in Golang.

Let’s start by discussing what the defer statement does in Golang programs.

The defer statement is used to schedule a function call so that it can be run after the function completes. Take a look at the example below:

package main
import "fmt"
func example1 () {
fmt.Println ("Welcome to Golang")
}
func example2 () {
fmt.Println ("This is an example of using Defer in Golang")
}
func main() {
defer example2()
example1 ()
}

What do you think will be the output of this Golang code?
This Golang code will print “Welcome to Golang” followed by “This is an example of using Defer in Golang.” The defer statement has been used to move the function call to the second so that it executes at the end of the function. Here’s how it’s executed:

func main () {
example1 ()
example2 ()
}

You might be thinking, “When should I use the defer statement with Golang functions?”

Well, you’ll be forced to use defer statement when you need to free the resources in your computer. For instance, if you open a file, and you wish to close it later, and then you can defer. Here’s an example:

f, _:= os.Open (filename)
defer f.Close ()

The arguments that are passed to the deferred function must be evaluated first when to defer function executes and not when the function call runs. This means that you shouldn’t worry much about whether the variables will be changing when your function executes—because there will only be a single deferred function call. Here’s an example:

for number := 0; i < 40; i++ {
defer fmt.Printf ("The number that you want is %d \n", number)
}

You should note that deferred functions are executed based on last in first out (LIFO) order. The advantages of using defer statement with Golang functions are threefold. First, it will help you to keep your close calls near your open call so that your code becomes easier to understand.

Second, if your function has many return statements—which in most cases makes your code appear “unclean”—then you can determine what to close. Third and finally, the deferred functions are easily run even during run-time panic times.

The Golang’s defer function is used in conjunction with panic and recover functions to handle run-time panic and recovery options. When used with both panic and recover functions, defer function can help you to free resources in your computer and make your program effective and efficient.

Next up, we look at both panic and recovery functions and how we can use them to have effective and efficient programs.

Golang’s panic and recover functions
The Golang’s panic function is used to define programmer error—such as accessing an index of an array that’s outside of bounds or forgetting to initialize the map—that ‘s hard to recover from. Here’s an example of Golang code that demonstrates how the panic function works in Golang:

package main
import "fmt"
func main() {
panic ("This is an error that’s difficult to recover from")
a := recover()
fmt.Println (a)
}

In the above example, the call to recover may never occur because it immediately stops the execution of the function call. However, when used with deferring, it changes the execution of the function call. Here’s an example of such a code:

package main
import "fmt"
func main() {
defer func () {
a := recover( )
fmt.Println (“The value of a is:”, a)
}( )
panic ("This is an error that’s difficult to recover from ")
}

Now you can start using defer function to help you manage errors in Golang.

GET YOUR FREE Golang EBOOK!

(Visited 393 times, 1 visits today)

Comments