There is a good design in the go language, the deferred (defer) statement, where you can add multiple defer statements to a function. When the function executes to the last, these defer statements are executed in reverse order, and finally the function returns. Especially when you are doing some open resources operation, encountered errors need to return early, before returning you need to close the corresponding resources, otherwise it is easy to cause problems such as resource leakage. As shown in the following code, we generally write open a resource that works like this:
Func ReadWrite () bool {
file. Open ("file")
//Do some work
if Failurex {
file. Close ()
return False
}
if Failurey {
file. Close ()
return False
}
file. Close ()
return True
}
We see a lot of duplicated code on it, and the go defer effectively solves this problem. With it, not only is the amount of code reduced a lot, but the program becomes more elegant. The function specified after defer is called before the function exits.
Func ReadWrite () bool {
file. Open ("file")
defer file. Close ()
if Failurex {
return false
}
if Failurey {
return false
}
return True
}
If there are many calls to defer, then defer is in LIFO mode, so the following code will output 4 3 2 1 0
For I: = 0; I < 5; i++ {
defer FMT. Printf ("%d", i)
}