当前位置:网站首页>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
defer
Keyword call timing and multiple callsdefer
How is the execution order determined ;defer
Keyword 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
边栏推荐
- 直方图均衡化
- xxl-job惊艳的设计,怎能叫人不爱
- How do microservices aggregate API documents? This wave of show~
- After unplugging the network cable, does the original TCP connection still exist?
- 什么是权限?什么是角色?什么是用户?
- Golang Modules
- Hands on deep learning (32) -- fully connected convolutional neural network FCN
- Four common methods of copying object attributes (summarize the highest efficiency)
- Global and Chinese market of planar waveguide optical splitter 2022-2028: Research Report on technology, participants, trends, market size and share
- Hands on deep learning (35) -- text preprocessing (NLP)
猜你喜欢
Hands on deep learning (32) -- fully connected convolutional neural network FCN
Hands on deep learning (38) -- realize RNN from scratch
Svg image quoted from CodeChina
PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
Regular expression (I)
Nuxt reports an error: render function or template not defined in component: anonymous
回复评论的sql
C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area
C # use ffmpeg for audio transcoding
C语言指针面试题——第二弹
随机推荐
[on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
Dynamic analysis and development prospect prediction report of high purity manganese dioxide in the world and China Ⓡ 2022 ~ 2027
Reading notes on how to connect the network - hubs, routers and routers (III)
回复评论的sql
ArrayBuffer
查看CSDN个人资源下载明细
Golang Modules
System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
Regular expression (I)
How do microservices aggregate API documents? This wave of show~
华为联机对战如何提升玩家匹配成功几率
xxl-job惊艳的设计,怎能叫人不爱
2022-2028 global gasket plate heat exchanger industry research and trend analysis report
H5 audio tag custom style modification and adding playback control events
Investment analysis and future production and marketing demand forecast report of China's paper industry Ⓥ 2022 ~ 2028
2022-2028 global strain gauge pressure sensor industry research and trend analysis report
Leetcode (Sword finger offer) - 35 Replication of complex linked list
Reading notes of how the network is connected - understanding the basic concepts of the network (I)
Flutter 小技巧之 ListView 和 PageView 的各种花式嵌套
直方图均衡化