What is the defer statement?
In Go, a defer
statement gives you the ability to execute a function AFTER its containing function has finished execution.
The easiest way to think about it is a callback, or a finally block for developers more familiar with Java.
You will commonly see defer statements being used to clean up resources, such as files and database connections.
defer Statement Syntax
func main() {
myFile, err := os.Open("my-file.txt")
defer myFile.close()
if err != nil {
panic(err)
}
}
The above is an example of using defer
to clean up resources, in this case, closing a file after we are done with it. The defer
statement will not execute until after our main
method has finished its execution.
Using defer directly after opening a resource that needs to be manually closed or handled (like files!) is a best practice. This way you know for sure there be no left over resources and you won't forget to manually close it later on in the code.
I like to keep such defer statements as close as possible, ideally right under, the line that opens the resources.
Using Multiple Defer statements
defer
statements are placed on a stack. Meaning the last defined statement will be the first to be executed. This is something I had to learn the hard way after facing a particularly confusing bug!
Consider the following code:
import "fmt"
func main() {
defer deferredPrint("0")
defer deferredPrint("1")
defer deferredPrint("2")
}
func deferredPrint(s string) {
fmt.Printf("%s\n", s)
}
What might its output be?
Since defer
statements are placed in a call stack (LIFO) the output is the following:
2
1
0
Notice that the last defined defer
statement is executed first!
Top comments (1)
This ended up posting a million times because idk how dev.to editing works 🙃