码迷,mamicode.com
首页 > 其他好文 > 详细

Defer 声明的设计理念

时间:2015-02-05 23:04:25      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

Defer 声明的设计理念

  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.(够本释放是Windows编程中的大问题)

  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.

Defer的三大原则

  The behavior of defer statements is straightforward and predictable. There are three simple rules:

1. 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.

  技术分享

2. Deferred function calls are executed in Last In First Out order after_the surrounding function returns.

  This function prints "3210":

  技术分享

3. 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:

  技术分享

参考:http://blog.golang.org/defer-panic-and-recover

Defer 声明的设计理念

标签:

原文地址:http://www.cnblogs.com/tekkaman/p/4276034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!