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

  • 相关阅读:
    python-列表基本方法
    成员/身份运算
    python-字符串常用方法
    python基础知识1
    jmeter_性能测试及报告分析
    Day3_linux_工作目录切换命令
    Day2_linux_查看系统状态
    Day1_liunx_常用系统工作命令
    互联网是有记忆的
    第3章 Python基础
  • 原文地址:https://www.cnblogs.com/tekkaman/p/4276034.html
Copyright © 2011-2022 走看看