当前位置:网站首页>go语言defer
go语言defer
2022-06-30 10:31:00 【wuydsec】
/** * @Author: wyd * @Description:defer * @File: 函数 * @Version: 1.0.0 * @Date: 2022/6/28 16:59 * @Blog: https://wuyandao.blog.csdn.net/ */
package main
import "fmt"
//func sum(x, y int) (ret int) {
// return x + y
//}
//func main() {
// //r := sum(4, 2)
// //fmt.Println(r)
// deferdemo()
//}
//Go语言中的defer语句会将其后面跟随的语句进行延迟处理。在defer归属的函数即将返回时,将延迟处理的语句按defer定义的逆序进行执行,也就是说,先被defer的语句最后被执行,最后被defer的语句,最先被执行。
//defer语句
//defer多用于函数结束之前的资源释放(文件句柄,数据库连接,socket连接)
//func deferdemo() {
// fmt.Println("heiheihei")
// defer fmt.Println("水水水水")
// fmt.Println("叽叽叽叽")
//}
在Go语言的函数中return语句在底层并不是原子操作,它分为给返回值赋值和RET指令两步。而defer语句执行的时机就在返回值赋值操作后,RET指令执行前。具体如下图所示:
//defer面试题
func f1() int {
x := 5
defer func() {
x++
}()
return x
}
func f2() (x int) {
defer func() {
x++
}()
return 5
}
func f3() (y int) {
x := 5
defer func() {
x++
}()
return x
}
func f4() (x int) {
defer func(x int) {
x++
}(x)
return 5
}
func main() {
fmt.Println(f1())
fmt.Println(f2())
fmt.Println(f3())
fmt.Println(f4())
}

边栏推荐
- Android 开发面试真题进阶版(附答案解析)
- 如何解决跨域
- MySQL导出sql脚本文件
- MATLAB image histogram equalization, namely spatial filtering
- 无心剑中译狄金森《灵魂择其伴侣》
- Input a decimal data, convert to 8, using the sequence stack
- 【STL源码剖析】迭代器
- What is erdma as illustrated by Coptic cartoon?
- LVGL 8.2 Checkboxes as radio buttons
- My in-depth remote office experience | community essay solicitation
猜你喜欢

Q-Learning笔记

Use keil5 software to simulate and debug gd32f305 from 0

File sharing server
![[STL source code analysis] container (to be supplemented)](/img/69/0c6e0e8ecb3ebc8c9b8503f5a8b4e5.jpg)
[STL source code analysis] container (to be supplemented)

数学知识复习:第二型曲线积分

我们公司使用 7 年的这套通用解决方案,打通了几十个系统,稳的一批!

Pytorch Notebook. Nn. Batchnorm1d

焕发青春的戴尔和苹果夹击,两大老牌PC企业极速衰败

The two e-commerce bigwigs' lacy news screens represent the return of e-commerce to normal, which will be beneficial to the real economy

电商两位大佬花边新闻刷屏,代表电商回归正常,将有利于实体经济
随机推荐
iptables目标TPROXY
MATLAB image histogram equalization, namely spatial filtering
sublist3r报错解决
Mysql database foundation: constraint and identification columns
Deep dive kotlin synergy (18): hot and cold data flow
Use keil5 software to simulate and debug gd32f305 from 0
LeetCode Algorithm 86. 分隔链表
JS FAQs
Rejuvenated Dell and apple hit each other, and the two old PC enterprises declined rapidly
List introduction
Go zero micro Service Practice Series (VIII. How to handle tens of thousands of order requests per second)
My in-depth remote office experience | community essay solicitation
Skill sorting [email protected]+ Alibaba cloud +nbiot+dht11+bh1750+ soil moisture sensor +oled
Remember the experience of an internship. It is necessary to go to the pit (I)
时间复杂度与空间复杂度
深潜Kotlin协程(十八):冷热数据流
Pycharm项目使用pyinstalle打包过程中问题及解决方案
[机缘参悟-34]:光锥之内皆命运
DQN笔记
Typescript – classes in Es5, inheritance, static methods