当前位置:网站首页>Defer
Defer
2022-04-21 06:37:00 【熊小憨】
作用
用于确保在程序执行的后期调用函数。通常用于清理目的。
案例
首先实现方法:
func createFile(p string) *os.File {
fmt.Println("creating")
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func writeFile(f *os.File) {
fmt.Println("writing")
fmt.Fprintln(f, "data")
}
func closeFile(f *os.File) {
fmt.Println("closing")
err := f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error:%v\n", err)
os.Exit(1)
}
}
然后调用方法,实现文件创建、数据写入、文件关闭的功能。
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
最终运行结果如下:
creating
writing
closing
版权声明
本文为[熊小憨]所创,转载请带上原文链接,感谢
https://blog.csdn.net/suma110/article/details/124172453
边栏推荐
- 树状数组
- About multithreading
- Longxun series: lt8911, transfer chip for converting LVDS / Mipi DSI signal into EDP signal, lt8619, HDMI / MHL signal into LVDS / RGB signal
- leetcode 27.移除元素
- Environment Variables
- 论文阅读:Domain Name Encryption Is Not Enough: Privacy Leakage via IP-based Website Fingerprinting
- Ctf-rsa decryption script
- 【WPF】数据模板选择器DataTemplateSelector
- Financial information security training - 22 / 4 / 18
- Number
猜你喜欢

Set up MySQL master-slave replication, read-write separation, one master and one slave

中介者模式(3.28-4.3)

MySQL数据库运行代码后,中文显示的是问号 ?

策略模式(2.28-3.6)

Guanghuaxin audio codec Daquan cjc4344, cjc8988, cjc5340, cjc6811 guanghuaxin audio codec, cjc4344, cjc8988, cs5340

【C#】重塑矩阵(交错数组)

NP、OSPF Stub区域

论文阅读:Measuring the Impact of a Successful DDoS Attack on the Customer Behaviour of Managed DNS Servi

BGP 认证功能

Sort method ----- > Hill sort, heap sort
随机推荐
Nmap scanning and scapy projects
synchronized的底层的三种上锁实现方式:(3.21-3.27)
leetcode 707.设计链表
NP、OSPF邻居邻接关系
OSPF多区域
H + background UI framework, click the button to create a new tab
MySQL common table structure
Sort method ----- > Hill sort, heap sort
Voisins bgp
2020-12-24
NP、OSPF Stub區域
【WPF】UpdateSourceTrigger
Blue Bridge Cup - palindromes and special palindromes
NP and OSPF monitoring and commissioning
NP, OSPF Stub Area
Signals
【WPF】自定义控件
Longxun series: lt8911, transfer chip for converting LVDS / Mipi DSI signal into EDP signal, lt8619, HDMI / MHL signal into LVDS / RGB signal
命令模式(3.21-3.27)
Ruiyuan power chip, ry3715, ry3750 replacement: silijie sy7208, sy7152, Xinpeng micro ap2008 Core source mp1542, mp3213. Input voltage from 2.5V to 5.5V