序
本文主要研究一下golang的defer
对于命名返回值
),然后执行defer,最后函数返回// f returns 42
func f() (result int) {
defer func() {
// result is accessed after it was set to 6 by the return statement
result *= 7
}()
return 6
}
这里return先给result赋值为6,之后执行defer,result变为42,最后返回42
func f() int {
result := 6
defer func() {
// result is accessed after it was set to 6 by the return statement
result *= 7
}()
return result
}
这里return确定返回值6,之后defer修改result,最后函数返回return确定的返回值
func multiDefer() {
for i := 3; i > 0; i-- {
defer func(n int) {
fmt.Print(n, " ")
}(i)
}
for i := 3; i > 0; i-- {
defer fmt.Print(i, " ")
}
}
多个defer函数,按顺序逆序执行,这里输出1 2 3
var fc func() string
func main() {
fmt.Println("hello")
defer fc()
}
由于defer指定的func为nil,这里panic
func main() {
for i := 3; i > 0; i-- {
defer func() {
fmt.Print(i, " ")
}()
}
}
由于defer这里调用的func没有参数,等执行的时候,i已经为0,因而这里输出3个0
defer可以拆解为return赋值,defer执行,最后代码返回三步;defer的顺序按逆序执行。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有