当前位置:网站首页>Go language defer
Go language defer
2022-06-30 11:07:00 【wuydsec】
/** * @Author: wyd * @Description:defer * @File: function * @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 In language defer Statement will delay the statement that follows it . stay defer When the belonging function is about to return , Press the deferred statement to defer The definition is executed in reverse order , in other words , Be first defer The statement of is finally executed , Finally being defer The sentence of , First executed .
//defer sentence
//defer Mostly used for resource release before the end of a function ( File handle , Database connection ,socket Connect )
//func deferdemo() {
// fmt.Println("heiheihei")
// defer fmt.Println(" Water... Water ")
// fmt.Println(" Jijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijijiji ")
//}
stay Go In the function of language return Statements are not atomic at the bottom , It is divided into assignment of return value and RET Command two steps . and defer The execution time of the statement is just after the return value assignment operation ,RET Before the command is executed . The details are shown in the following figure :
//defer Interview questions
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())
}

边栏推荐
- [rust daily] the first rust monthly magazine on January 22, 2021 invites everyone to participate
- 中移OneOS开发板学习入门
- pytorch 笔记:validation ,model.eval V.S torch.no_grad
- From introduction to mastery of MySQL 50 lectures (32) -scylladb production environment cluster building
- 8行代码实现快速排序,简单易懂图解!
- 在 sCrypt 中实现高效的椭圆曲线点加法和乘法
- MySQL导出sql脚本文件
- 经典面试题:负责的模块,针对这些功能点你是怎么设计测试用例的?【杭州多测师】【杭州多测师_王sir】...
- 【STL源码剖析】迭代器
- 焕发青春的戴尔和苹果夹击,两大老牌PC企业极速衰败
猜你喜欢
随机推荐
DataX JSON description
【STL源码剖析】容器(待补充)
国产自研系统的用户突破4亿,打破美国企业的垄断,谷歌后悔不迭
WireGuard简单配置
[proteus simulation] Arduino uno led simulated traffic light
sublist3r报错解决
CP2112使用USB转IIC通信教学示例
SQL必需掌握的100个重要知识点:创建和操纵表
Unity Shader - 踩坑 - BRP 管线中的 depth texture 的精度问题(暂无解决方案,推荐换 URP)
SQL必需掌握的100个重要知识点:使用子查询
SQL必需掌握的100个重要知识点:组合查询
深潜Kotlin协程(十八):冷热数据流
From introduction to mastery of MySQL 50 lectures (32) -scylladb production environment cluster building
LiveData源码赏析三 —— 常见问题
Review of mathematical knowledge: curve integral of the second type
OLAP数据库引擎如何选型?
Wireguard simple configuration
LVGL 8.2图片缩放及旋转
LVGL8.2 Simple Checkboxes
The intelligent DNA molecular nano robot model is coming







