This is a creation in Article, where the information may have evolved or changed.
53. Toad Notes Go language--defer,panic,recover usage scene
Defer
The function called by defer is temporarily saved to the invocation list. The saved invocation list is executed when the current environment returns. Defer can typically be used to simplify code and perform various cleanup operations.
The behavior of the defer statement is simple and predictable. There are three basic principles:
1. When defer invokes a function, the value of each parameter and variable used by the function is also evaluated
2. The function called by defer will be executed in a last-in-first-out order when the current function returns.
3. A function called by defer can read or modify a named return value after the return statement executes. With this feature, we can easily modify the error return value of a function.
Panic
Panic is a built-in function: Stop the current control flow and start panicking. When the F function calls panic, the F function stops executing the subsequent normal statement, but the previous defered function call is still executed normally and then returned to the caller of F. For callers of the F function, the behavior of F is similar to calling the panic function directly. The above process will always go along the call stack until the current goroutine return causes the program to crash! Panics can be triggered either directly by calling panic, or by some run-time errors, such as an out-of-bounds access to an array.
Recover
Recover is also a built-in function: used to recover from panicking. The use of Recover and defer can be very useful. For a normal execution process, calling recover will return nil and have no effect. However, if the current goroutine is in the panicking state, the recover call captures the parameters when the panic is triggered and reverts to the normal execution process.
The sample code is as follows:
Package Main
Import "FMT"
func Main () {
f ()
FMT. PRINTLN ("returnednormallyfromF.")
}
func f () {
deferfunc(){
ifr:=recover(); r!=Nil{
FMT. Println ("recoveredinF", R)
}
}()
FMT. Println ("callingG.")
g (0)
FMT. PRINTLN ("returnednormallyfromG.")
}
func g (iint) {
ifi>3{
FMT. Println ("panicking!")
Panic(fmt. Sprintf ("%v", i))
}
deferFMT. Println ("Defering", i)
FMT. Println ("Printinging", i)
g (i+1)
}
EXECUTE as follows:
Calling G.
Printing in G 0
Printing in G 1
Printing in G 2
Printing in G 3
panicking!
Defer in G 3
Defer in G 2
Defer in G 1
Defer in G 0
Recovered in F 4
Returnednormally from F.
Defer statements (whether or not including panic and recover) provide an unusual and powerful control flow mechanism. It can be used to simulate some special grammatical structures in some other languages.