当前位置:网站首页>Golang defer
Golang defer
2022-07-04 09:32:00 【动态一时爽,重构火葬场】
在Golang使用defer常常会迷惑于以下两个问题
defer关键字的调用时机以及多次调用defer时执行顺序是如何确定的;defer关键字使用传值的方式传递参数时会进行预计算,导致不符合预期的结果;
defer的调用时机是在当前函数返回之前调用的,执行顺序是先入后出。
预计算参数
defer也是传参的。比如说以下代码就会输入0,而不是最终的1
n := 0
defer fmt.Println(n)
n = 1
其原因在于defer会立刻拷贝defer函数中引用的外部参数,也就是说运行到defer fmt.Println(n)时,n的值便已经在defer函数里面啦
即使defer的是个有参方法,也会拷贝到参数
func TestDeferPassParmFunc(t *testing.T) { n := 0 defer deferPassParam(n) n = 1 } func deferPassParam(r int) { fmt.Println(r) } // output: // 0
如果想避免这种情况我们可以defer匿名函数或者指针参数函数
func TestDeferPassParmFunc(t *testing.T) {
n := 0
defer deferPassParam(&n)
n = 1
}
func deferPassParam(r *int) {
fmt.Println(*r)
}
// output:
// 1
常见defer现象
连续defer,先入后出
按照先入后出执行
defer fmt.Println("one")
defer fmt.Println("two")
defer fmt.Println("three")
// output:
// three
// two
// one
defer声明,变量确认
变量在defer声明时便已经确认,即使后面变量发生改变,defer实际执行时也与声明时保持一致。
n := 0
defer fmt.Println(n)
n = 1
// output:
// 0
defer闭包,参数可修改
对于有名返回值,被defer的函数是闭包,且该函数为命名返回值,那么defer是可以访问返回值,并修改
func namedReturn() (r int) {
defer func() {
r = 1
}()
return 2
}
// output
// 1
当然,如果被defer的函数不是闭包或匿名,但是只要传入有名返回值的指针,其实还是可以的
func namedReturnWithDeferNamedFunc() (r int) { defer namedFuncForDer(&r) return 2 } func namedFuncForDer(r *int) { *r = 1 } // output // 1
除了命名返回值这种特殊参数外,其他普通参数其他也可访问修改
// 无参匿名
n := 1
defer func() {
fmt.Println(n)
}()
n = n + 1
return n
// output:
// 2
// 有参匿名
n := 1
defer func(x int) {
fmt.Println(n)
}(n)
n = n + 1
return n
// output:
// 2
总结
- defer按照栈顺序,先定义的后执行
- defer闭包会在defer执行时,获取或改变闭包内变量(但不改变非命名返回值)
- defer匿名函数也会获取或者改变闭包内变量(但不改变非命名返回值)
- defer普通函数,在非指针参数情况下,与defer声明时变量值一致
Ref
- https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-defer
边栏推荐
- 《网络是怎么样连接的》读书笔记 - 认识网络基础概念(一)
- Report on the development trend and prospect trend of high purity zinc antimonide market in the world and China Ⓕ 2022 ~ 2027
- Problems encountered by scan, scanf and scanln in golang
- Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
- Analysis report on the development status and investment planning of China's modular power supply industry Ⓠ 2022 ~ 2028
- How to batch change file extensions in win10
- Deadlock in channel
- Target detection -- intensive reading of yolov3 paper
- C language - Introduction - Foundation - syntax - [identifier, keyword, semicolon, space, comment, input and output] (III)
- Research Report on research and investment prospects of China's testing machine industry (2022 Edition)
猜你喜欢

Dede plug-in (multi-function integration)

ArrayBuffer
![[C Advanced] file operation (2)](/img/50/e3f09d7025c14ee6c633732aa73cbf.jpg)
[C Advanced] file operation (2)

Latex download installation record

MySQL foundation 02 - installing MySQL in non docker version

Logstack configuration details -- elasticstack (elk) work notes 020

After unplugging the network cable, does the original TCP connection still exist?

Some points needing attention in PMP learning

2022-2028 global elastic strain sensor industry research and trend analysis report

2022-2028 global seeder industry research and trend analysis report
随机推荐
Launpad | 基础知识
Awk from digging into the ground to getting started (10) awk built-in functions
Latex download installation record
Global and Chinese markets for laser assisted liposuction (LAL) devices 2022-2028: Research Report on technology, participants, trends, market size and share
Problems encountered by scan, scanf and scanln in golang
Analysis report on the production and marketing demand and investment forecast of tellurium dioxide in the world and China Ⓣ 2022 ~ 2027
Write a jison parser from scratch (4/10): detailed explanation of the syntax format of the jison parser generator
Flutter tips: various fancy nesting of listview and pageview
C语言-入门-基础-语法-数据类型(四)
The 14th five year plan and investment risk analysis report of China's hydrogen fluoride industry 2022 ~ 2028
Investment analysis and prospect prediction report of global and Chinese high purity tin oxide Market Ⓞ 2022 ~ 2027
How does idea withdraw code from remote push
UML 时序图[通俗易懂]
MySQL transaction mvcc principle
Dynamic analysis and development prospect prediction report of high purity manganese dioxide in the world and China Ⓡ 2022 ~ 2027
Solution to null JSON after serialization in golang
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
Research Report on research and investment prospects of China's testing machine industry (2022 Edition)
In depth research and investment strategy report on China's hydraulic parts industry (2022 Edition)
Reload CUDA and cudnn (for tensorflow and pytorch) [personal sorting summary]