首页 技术 正文
技术 2022年11月11日
0 收藏 334 点赞 3,542 浏览 1474 个字

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:

  Defer 声明的设计理念

  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 声明的设计理念

  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.

  Defer 声明的设计理念

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

  This function prints “3210”:

  Defer 声明的设计理念

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:

  Defer 声明的设计理念

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,812
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,894