当前位置:网站首页>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
边栏推荐
- 2022-2028 global protein confectionery industry research and trend analysis report
- 2022-2028 global tensile strain sensor industry research and trend analysis report
- Pueue data migration from '0.4.0' to '0.5.0' versions
- Hands on deep learning (33) -- style transfer
- How do microservices aggregate API documents? This wave of show~
- Svg image quoted from CodeChina
- Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310
- pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.
- Summary of small program performance optimization practice
- Rules for using init in golang
猜你喜欢
Markdown syntax
2022-2028 global special starch industry research and trend analysis report
Hands on deep learning (32) -- fully connected convolutional neural network FCN
PHP personal album management system source code, realizes album classification and album grouping, as well as album image management. The database adopts Mysql to realize the login and registration f
Regular expression (I)
C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area
技术管理进阶——如何设计并跟进不同层级同学的绩效
ASP. Net to access directory files outside the project website
C # use ffmpeg for audio transcoding
2022-2028 global intelligent interactive tablet industry research and trend analysis report
随机推荐
Multilingual Wikipedia website source code development part II
Trim leading or trailing characters from strings- Trim leading or trailing characters from a string?
Luogu deep foundation part 1 Introduction to language Chapter 4 loop structure programming (2022.02.14)
Markdown syntax
Opencv environment construction (I)
Report on the development trend and prospect trend of high purity zinc antimonide market in the world and China Ⓕ 2022 ~ 2027
【leetcode】29. Divide two numbers
Launpad | 基礎知識
26. Delete duplicates in the ordered array (fast and slow pointer de duplication)
什么是uid?什么是Auth?什么是验证器?
SSM online examination system source code, database using mysql, online examination system, fully functional, randomly generated question bank, supporting a variety of question types, students, teache
How to batch change file extensions in win10
Fatal error in golang: concurrent map writes
浅谈Multus CNI
libmysqlclient.so.20: cannot open shared object file: No such file or directory
pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.
华为联机对战如何提升玩家匹配成功几率
智慧路灯杆水库区安全监测应用
PHP book borrowing management system, with complete functions, supports user foreground management and background management, and supports the latest version of PHP 7 x. Database mysql
mmclassification 标注文件生成