[翻译]Defer,Panic,and Recover
翻译的意义在于:如何更好的成就读者~
The Go Blog
Defer, Panic, and Recover
Andrew Gerrand
4 August 2010 [2010 年 8 月 4 号]
Go has the usual mechanisms for control flow: if, for, switch, goto. It also has the go statement to run code in a separate goroutine. Here I'd like to discuss some of the less common ones: defer, panic, and recover.
A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.
For example, let's look at a function that opens two files and copies the contents of one file to the other:
This works, but there is a bug. If the call to os.Create fails, the function will return without closing the source file. This can be easily remedied by putting a call to src.Close before the second return statement, but if the function were more complex the problem might not be so easily noticed and resolved. By introducing defer statements we can ensure that the files are always closed:
Defer statements allow us to think about closing each file right after opening it, guaranteeing that, regardless of the number of return statements in the function, the files will be closed.
The behavior of defer statements is straightforward and predictable. There are three simple rules:
A deferred function's arguments are evaluated when the defer statement is evaluated.
In this example, the expression "i" is evaluated when the Println call is deferred. The deferred call will print "0" after the function returns.
Deferred function calls are executed in Last In First Out order after the surrounding function returns.
This function prints "3210":
Deferred functions may read and assign to the returning function's named return values.
In this example, a deferred function increments the return value i after the surrounding function returns. Thus, this function returns 2:
This is convenient for modifying the error return value of a function; we will see an example of this shortly.
Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes. Panics can be initiated by invoking panic directly. They can also be caused by runtime errors, such as out-of-bounds array accesses.
Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution.
Here's an example program that demonstrates the mechanics of panic and defer:
译者注:以下是一个经典示例,
可以结合示例加深对defer,panic,recover的理解;
读者先自己尝试写出以下程序的输出,
然后对比分析自己的答案是否正确;
尤其 if r := recover(); r != nil
{ 这一行
那最终r的值是什么?
答案就是上述的经典描述:
If the current goroutine is panicking,
a call to recover will capture the value
given to panic and resume normal execution.?
The function g takes the int i, and panics if i is greater than 3, or else it calls itself with the argument i+1. The function f defers a function that calls recover and prints the recovered value (if it is non-nil). Try to picture what the output of this program might be before reading on.
The program will output:
If we remove the deferred function from f the panic is not recovered and reaches the top of the goroutine's call stack, terminating the program. This modified program will output:
For a real-world example of panic and recover, see the json package from the Go standard library. It encodes an interface with a set of recursive functions. If an error occurs when traversing the value, panic is called to unwind the stack to the top-level function call, which recovers from the panic and returns an appropriate error value (see the 'error' and 'marshal' methods of the encodeState type in encode.go).
The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values.
Other uses of defer (beyond the file.Close example given earlier) include releasing a mutex:
printing a footer:
and more.
In summary, the defer statement (with or without panic and recover) provides an unusual and powerful mechanism for control flow. It can be used to model a number of features implemented by special-purpose structures in other programming languages. Try it out.
版权声明: 本文为 InfoQ 作者【卓丁】的原创文章。
原文链接:【http://xie.infoq.cn/article/215572752958e888eaece8d5d】。文章转载请联系作者。
评论