Video Coming Soon...
12: Flow Control: defer
WARNING This exercise is in DRAFT status, so there may be errors. If you find any, please email me at help@learncodethehardway.com so I can fix them.
Let's have a fun little break and see if you can figure out what defer
does from the code below:
View Source file ex12/main.go Only
package main
import (
"fmt"
)
func PrintThis(thing string) {
fmt.Println(thing)
}
func main() {
PrintThis("START")
defer PrintThis("one")
defer PrintThis("two")
defer PrintThis("three")
defer PrintThis("four")
defer PrintThis("five")
PrintThis("END")
}
Get it working, run it, and then try to explain what's going on. I'll give you a hint: "Programmers are not nearly as smart as you think. If it says defer, that's probably what it does."
Solution
The defer
keyword is deceptively simple but adds many nice benefits to your code. Hopefully you figured out that it delays the call of a function until the end of that block. That's also why I said that its name is what it does. Many times you'll find that if you over think what programmers make you'll end up getting it wrong. Programmers are mostly trying to keep things simple these days, and weird names for stuff is usually avoided. Usually. If you're not a Haskell programer. Or C++. Or Java. Or...
Anyway, the reason for defer
existing is to clean up resources that your functions create when they exit or when there's an error. Since the defer runs no matter what (with some exceptions) when the function ends then you can put things like closing files in a defer
right after opening the file like this:
import (
"os"
"fmt"
)
func main() {
my_file, err := os.Open("somefile")
defer my_file.Close()
if err != nil { fmt.Println("file open failed")
}
In this code I open a file with os
, and then immediately use defer my_file.Close()
to make sure that the file is closed no matter how it exits. The , err
part of that line is related to error handling which we'll cover next, but maybe you can figure it out now.
The Practice
- Break It -- Remember I said that
defer
runs mostly all the time? There's a nice library calledlog
you can use that has a functionlog.Fatal()
. Try using that and see how defer works with it. - Change It -- How crazy can you get with defer?
- Remake It -- As usual, write a description the recreate it from memory using the description. The more you do this, the better you'll get.
Study Drills
I feel that defer
is simple enough that you don't need to drill it, but in the next exercise we learn about error handling where it will become more useful.
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.