当前位置:网站首页>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
边栏推荐
- Write a jison parser from scratch (1/10):jison, not JSON
- Are there any principal guaranteed financial products in 2022?
- Reading notes of how the network is connected - understanding the basic concepts of the network (I)
- Write a jison parser from scratch (6/10): parse, not define syntax
- Svg image quoted from CodeChina
- Global and Chinese markets of water heaters in Saudi Arabia 2022-2028: Research Report on technology, participants, trends, market size and share
- ArrayBuffer
- xxl-job惊艳的设计,怎能叫人不爱
- Research Report on the development trend and Prospect of global and Chinese zinc antimonide market Ⓚ 2022 ~ 2027
- Flutter 小技巧之 ListView 和 PageView 的各種花式嵌套
猜你喜欢

C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area

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

Svg image quoted from CodeChina

C # use ffmpeg for audio transcoding

2022-2028 global visual quality analyzer industry research and trend analysis report

IIS configure FTP website

Sort out the power node, Mr. Wang he's SSM integration steps

Write a mobile date selector component by yourself

2022-2028 global industrial gasket plate heat exchanger industry research and trend analysis report

How web pages interact with applets
随机推荐
Launpad | Basics
2022-2028 global small batch batch batch furnace industry research and trend analysis report
Global and Chinese markets of hemoglobin analyzers in care points 2022-2028: Research Report on technology, participants, trends, market size and share
PMP registration process and precautions
Simulate EF dbcontext with MOQ - mocking EF dbcontext with MOQ
Global and Chinese PCB function test scale analysis and development prospect planning report Ⓑ 2022 ~ 2027
2022-2028 global intelligent interactive tablet industry research and trend analysis report
Fatal error in golang: concurrent map writes
Write a jison parser from scratch (3/10): a good beginning is half the success -- "politics" (Aristotle)
品牌连锁店5G/4G无线组网方案
Go context 基本介绍
ArrayBuffer
How do microservices aggregate API documents? This wave of show~
2022-2028 global tensile strain sensor industry research and trend analysis report
Explanation of closures in golang
Hands on deep learning (33) -- style transfer
Global and Chinese markets of water heaters in Saudi Arabia 2022-2028: Research Report on technology, participants, trends, market size and share
Analysis report on the development status and investment planning of China's modular power supply industry Ⓠ 2022 ~ 2028
Global and Chinese trisodium bicarbonate operation mode and future development forecast report Ⓢ 2022 ~ 2027
H5 audio tag custom style modification and adding playback control events