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

  • 相关阅读:
    判断数组的方法
    介绍下 npm 模块安装机制,为什么输入 npm install 就可以自动安装对应的模块?
    因为这样那样的原因又滚回来了
    AFO成功
    SDOI2018
    TJOI2018
    杂题
    线段树合并
    几个dp的陈年老题
    【自家测试】2018-5-9
  • 原文地址:https://www.cnblogs.com/tekkaman/p/4276034.html
Copyright © 2011-2022 走看看