zoukankan      html  css  js  c++  java
  • Defer 声明的设计理念

    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

  • 相关阅读:
    Android在layout xml中使用include完成静态加载
    ImageSwitch图像切换控件
    合并石子大总结
    子矩阵(暴搜(全排列)+DP)
    回路(一笔画问题)
    道路重建(记忆化搜索+贪心)
    【NOIP2013 普及组】车站分级
    UML的基本关联
    Matlab画图-非常具体,非常全面
    面向对象程序设计与面向过程程序设计解析
  • 原文地址:https://www.cnblogs.com/tekkaman/p/4276034.html
Copyright © 2011-2022 走看看