当前位置:网站首页>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())
}

边栏推荐
- 【STL源码剖析】迭代器
- ionic4 ion-reorder-group组件拖拽改变item顺序
- Deep dive kotlin Xie Cheng (17): Actor
- 历史上的今天:微软收购 PowerPoint 开发商;SGI 和 MIPS 合并
- 在 sCrypt 中实现高效的椭圆曲线点加法和乘法
- How can the sports app keep the end-to-side background alive to make the sports record more complete?
- LVGL 8.2 re-coloring
- 智能DNA分子纳米机器人模型来了
- 吴恩达2022机器学习专项课测评来了!
- ArrayList与顺序表
猜你喜欢

Deep dive kotlin synergy (18): hot and cold data flow

ArrayList与顺序表

LVGL 8.2 Image

国产自研系统的用户突破4亿,打破美国企业的垄断,谷歌后悔不迭

Using LVM to resize partitions

Mysql database foundation: views and variables

What is erdma as illustrated by Coptic cartoon?

DQN笔记

Remember the experience of an internship. It is necessary to go to the pit (I)

Kernel linked list (general linked list) "list.h" simple version and individual comments
随机推荐
When does the database need to use the index [Hangzhou multi surveyors] [Hangzhou multi surveyors _ Wang Sir]
吴恩达2022机器学习专项课测评来了!
Collectors. Tomap application
Skill combing [email protected] control a dog's running on OLED
Machine learning interview preparation (I) KNN
China will force a unified charging interface. If Apple does not bow its head, iPhone will be kicked out of the Chinese market
Deep dive kotlin Xie Cheng (17): Actor
微信推出图片大爆炸功能;苹果自研 5G 芯片或已失败;微软解决导致 Edge 停止响应的 bug|极客头条...
[STL source code analysis] iterator
数学知识复习:第二型曲线积分
7 大轻量易用的工具,给开发者减压提效,助力企业敏捷上云 | Techo Day 精彩回顾...
MySQL导出sql脚本文件
软件测试工程师面试基础题(应届生和测试小菜必备)最基础的面试题
Double-DQN笔记
Gd32 RT thread DAC driver function
Smith chart view of semi steel coaxial RF line and RF line matching calibration of network analyzer e5071c
煥發青春的戴爾和蘋果夾擊,兩大老牌PC企業極速衰敗
59 websites programmers need to know
经典面试题:负责的模块,针对这些功能点你是怎么设计测试用例的?【杭州多测师】【杭州多测师_王sir】...
IDEA 又出新神器,一套代码适应多端!