// code_006_defer_usage project main.go
package main
import (
"fmt"
)
func test(x int) {
fmt.Println(100 / x)
}
func main() {
//关键字 defer ⽤于延迟一个函数或者方法(或者当前所创建的匿名函数)的执行。
//注意,defer语句只能出现在函数或方法的内部。
fmt.Println("this is a test")
defer fmt.Println("this is a defer")
//defer语句经常被用于处理成对的操作,如打开、关闭、连接、断开连接、加锁、释放锁。
//通过defer机制,不论函数逻辑多复杂,都能保证在任何执行路径下,资源被释放。
//释放资源的defer应该直接跟在请求资源的语句后。
//如果一个函数中有多个defer语句,它们会以LIFO(后进先出)的顺序执行。
//哪怕函数或某个延迟调用发生错误,这些调用依旧会被执⾏。
defer fmt.Println("aaaa")
defer fmt.Println("bbbb")
defer test(0)
defer fmt.Println("ccc")
a, b := 10, 20
defer func(x int) {
fmt.Println("\ndefer:", x, b) //b闭包引用
}(a)
a += 10
b += 100
fmt.Printf("a= %d, b= %d", a, b)
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- RabbitMQ延迟消息的延迟极限是多少?
- RabbitMQ延迟消息的延迟极限是多少?
- 延迟静态绑定——static
- RabbitMQ实现延迟队列
- mybatis 延迟加载
- mybatis教程--延迟加载详解
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Dream Machine
M. Mitchell Waldrop / Penguin Books / 2002-8 / USD 16.00
While most people may not be familiar with the name J. C. R. Licklider, he was the guiding spirit behind the greatest revolution of the modern era. At a time when most computers were big, ponderous ma......一起来看看 《The Dream Machine》 这本书的介绍吧!