当前位置:网站首页>Golang defer
Golang defer
2022-07-04 09:39:00 【Dynamic for a while, reconstructing the crematorium】
stay Golang Use defer Often confused by the following two questions
deferKeyword call timing and multiple callsdeferHow is the execution order determined ;deferKeyword pre calculation will be carried out when passing parameters by value , Lead to unexpected results ;
defer Is called before the current function returns , The execution order is first in then out .
Pre calculated parameters
defer It is also passed on . For example, the following code will be entered 0, Not the final 1
n := 0
defer fmt.Println(n)
n = 1
And the reason is that defer Will copy immediately defer External parameters referenced in the function , That is, run to defer fmt.Println(n) when ,n The value of is already in defer Inside the function
Even if defer Is a parametric method , It will also be copied to parameters
func TestDeferPassParmFunc(t *testing.T) { n := 0 defer deferPassParam(n) n = 1 } func deferPassParam(r int) { fmt.Println(r) } // output: // 0
If we want to avoid this situation, we can defer Anonymous function or pointer parameter function
func TestDeferPassParmFunc(t *testing.T) {
n := 0
defer deferPassParam(&n)
n = 1
}
func deferPassParam(r *int) {
fmt.Println(*r)
}
// output:
// 1
common defer The phenomenon
continuity defer, First in, then out
Execute according to "first in, then out"
defer fmt.Println("one")
defer fmt.Println("two")
defer fmt.Println("three")
// output:
// three
// two
// one
defer Statement , Variable confirmation
Variable in defer It has been confirmed at the time of declaration , Even if the following variables change ,defer The actual implementation is also consistent with the declaration .
n := 0
defer fmt.Println(n)
n = 1
// output:
// 0
defer Closure , Parameters can be modified
For the named return value , By defer The function of is closure , And this function is named return value , that defer Yes, you can access the return value , And modify it
func namedReturn() (r int) {
defer func() {
r = 1
}()
return 2
}
// output
// 1
Of course , If you are defer Functions of are not closures or anonymous , But just pass in a pointer with a named return value , Actually, it's OK
func namedReturnWithDeferNamedFunc() (r int) { defer namedFuncForDer(&r) return 2 } func namedFuncForDer(r *int) { *r = 1 } // output // 1
In addition to the special parameter named return value , Other common parameters can also be accessed and modified
// No parameter anonymous
n := 1
defer func() {
fmt.Println(n)
}()
n = n + 1
return n
// output:
// 2
// There are parameters anonymous
n := 1
defer func(x int) {
fmt.Println(n)
}(n)
n = n + 1
return n
// output:
// 2
summary
- defer In stack order , Define first and then execute
- defer Closure meeting in defer Execution time , Get or change variables in closures ( But do not change the unnamed return value )
- defer Anonymous functions also get or change variables in closures ( But do not change the unnamed return value )
- defer Ordinary function , In the case of non pointer parameters , And defer The variable values are consistent when declaring
Ref
- https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-defer
边栏推荐
- DR6018-CP01-wifi6-Qualcomm-IPQ6010-IPQ6018-FAMILY-2T2R-2.5G-ETH-port-CP01-802-11AX-MU-MIMO-OFDMA
- 华为联机对战如何提升玩家匹配成功几率
- 2022-2028 global gasket plate heat exchanger industry research and trend analysis report
- Lauchpad X | 模式
- 26. Delete duplicates in the ordered array (fast and slow pointer de duplication)
- After unplugging the network cable, does the original TCP connection still exist?
- Flutter 小技巧之 ListView 和 PageView 的各種花式嵌套
- Four common methods of copying object attributes (summarize the highest efficiency)
- About the for range traversal operation in channel in golang
- C # use smtpclient The sendasync method fails to send mail, and always returns canceled
猜你喜欢

Latex download installation record

How to ensure the uniqueness of ID in distributed environment

At the age of 30, I changed to Hongmeng with a high salary because I did these three things

Svg image quoted from CodeChina

xxl-job惊艳的设计,怎能叫人不爱

Four common methods of copying object attributes (summarize the highest efficiency)

libmysqlclient.so.20: cannot open shared object file: No such file or directory

Write a mobile date selector component by yourself

MATLAB小技巧(25)竞争神经网络与SOM神经网络

C # use ffmpeg for audio transcoding
随机推荐
2022-2028 global special starch industry research and trend analysis report
浅谈Multus CNI
2022-2028 global optical transparency industry research and trend analysis report
Markdown syntax
Explanation of closures in golang
How to display √ 2 on the command line terminal ̅? This is actually a blog's Unicode test article
Research Report on the development trend and Prospect of global and Chinese zinc antimonide market Ⓚ 2022 ~ 2027
Launpad | 基础知识
C # use smtpclient The sendasync method fails to send mail, and always returns canceled
Kotlin 集合操作汇总
Analysis report on the production and marketing demand and investment forecast of tellurium dioxide in the world and China Ⓣ 2022 ~ 2027
MATLAB小技巧(25)竞争神经网络与SOM神经网络
"How to connect the Internet" reading notes - FTTH
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
Multilingual Wikipedia website source code development part II
Fatal error in golang: concurrent map writes
HMS core helps baby bus show high-quality children's digital content to global developers
Hands on deep learning (34) -- sequence model
2022-2028 global tensile strain sensor industry research and trend analysis report
Pueue data migration from '0.4.0' to '0.5.0' versions