Golang知识点记录 -- defer
source link: https://studygolang.com/articles/35569
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Golang知识点记录 -- defer
hongtj · 1天之前 · 361 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览defer规则总是记不住,在此记录一下。
f1()、f2()、f3()、f4()、f5() 函数分别返回什么?
func f1() (r int) {
defer func() {
r++
}()
return 0
}
func f2() (r int) {
t := 5
defer func() {
t = t + 5
}()
return t
}
func f3() (r int) {
defer func(r int) {
r = r + 5
}(r)
return 1
}
func f4() int {
var i int
defer func() {
i++
}()
return 1
}
func f5() int {
var i int
defer func() {
i++
}()
return i
}
参考答案及解析:1 5 1 1 0
知识点:defer、返回值
defer规则
1.1 规则一:延迟函数的参数在defer语句出现时就已经确定下来了
1.2 规则二:延迟函数执行按后进先出顺序执行,即先出现的defer最后执行
1.3 规则三:延迟函数可能操作主函数的具名返回值
1.3.1 函数返回过程
1.3.1 主函数拥有匿名返回值,返回字面值
1.3.2 主函数拥有匿名返回值,返回变量
1.3.3 主函数拥有具名返回值
有疑问加站长微信联系(非本文作者)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK