Go defer Keyword

beginner
15 min

Go defer Keyword

Welcome to a comprehensive guide on the Go defer keyword! In this lesson, we'll explore the defer keyword, its purpose, and how to use it effectively in your Go programs. Let's dive in! 🎯

What is the defer keyword?

The defer keyword in Go is used to defer the execution of a function call until the current function returns. This can be particularly useful when you have cleanup operations, such as closing connections or freeing resources, that should be performed at the end of the function. 💡

Why use the defer keyword?

Using the defer keyword ensures that the deferred function calls are executed in the reverse order of their appearance within the function, no matter how control flows (e.g., through loops or if statements). This is a powerful tool for handling resources efficiently and writing cleaner, more maintainable code. ✅

Basic Example

Let's start with a simple example that demonstrates the use of the defer keyword:

go
package main import "fmt" func main() { defer sayGoodbye() fmt.Println("Hello, World!") sayHello() } func sayHello() { fmt.Println("Hello!") } func sayGoodbye() { fmt.Println("Goodbye!") }

In this example, sayGoodbye() is deferred, and it will be executed after the main() function returns, regardless of the order of the statements within the function. When you run this program, the output will be:

Hello, World! Hello! Goodbye!

Deferred Function Arguments

Deferred function calls can also take arguments. The values of variables at the time of the defer call are used for the arguments.

go
package main import "fmt" func main() { x := 10 defer greet("World", x) fmt.Println("Hello, ") x = 20 } func greet(name, number int) { fmt.Printf("Hello, %s! You are number %d.\n", name, number) }

In this example, greet is a deferred function that takes two arguments. When the function is called, x has a value of 10. The output of this program is:

Hello, (empty space because we didn't print anything) Hello, World! You are number 10.

Practical Application

One common use case for the defer keyword is in handling errors. You can use the defer keyword to ensure that errors are properly handled, even if the error occurs deep within a function hierarchy. Here's an example:

go
package main import ( "fmt" "io/ioutil" "log" "os" ) func main() { err := openFile("test.txt") if err != nil { log.Fatal(err) } defer fileClose(err) contents, err := ioutil.ReadAll(os.Stdin) if err != nil { log.Fatal(err) } err = writeToFile(contents, "test.txt") if err != nil { log.Fatal(err) } } func openFile(filename string) (file *os.File, err error) { file, err = os.OpenFile(filename, os.O_RDONLY, 0) return } func writeToFile(data []byte, filename string) error { file, err := openFile(filename) if err != nil { return err } defer file.Close() _, err = file.Write(data) return err } func fileClose(err error) { if err != nil { log.Println("Closing file:", err) } }

In this example, we have a simple program that reads input from stdin, writes it to a file, and closes the file after the write operation. The defer keyword is used to ensure that the file is closed, regardless of whether there is an error during the write operation or not.

Quiz

Quick Quiz
Question 1 of 1

What does the `defer` keyword do in Go?

Conclusion

The defer keyword is an essential tool in the Go programmer's arsenal, allowing for clean and efficient handling of resources and error management. We hope this lesson has helped you understand the concept and shown you how to use it effectively in your Go programs. Happy coding! 📝