What is the actual use of the defer
keyword?
for example, instead of writing this:
func main() {
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
I can just write this:
func main() {
f := createFile("/tmp/defer.txt")
writeFile(f)
closeFile(f)
}
So, why should I use it instead of a usual placing of functions?
Deferred functions always get executed, even after a panic or return statement.
In real world code a lot of stuff happens between Open/Close type of call pairs, and defer lets you keep them close together in the source, and you don't have to repeat the Close call for every return statement.
Go and write some real code. The usefulness of defer will be blatantly obvious before long.
Very useful when catching code that has the potential to panic.
Often when using interface{}
(an "any" type) or reflection, you will encounter issues where you are trying to cast to a type that doesn't match the actual type of the data.
defer
ing a function at the top to handle that error is how you save the day and keep your application running.