mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-23 15:32:15 +08:00
docs: Defer 延时执行
This commit is contained in:
parent
d24bbf5d69
commit
16a819821e
34
base/function/defer/main.go
Normal file
34
base/function/defer/main.go
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// golang 函数中 return 不是原子操作 底层分为 两步 执行
|
||||||
|
// 1. 返回值赋值 (如果 没有 指定返回值 变量名 则为内部的一个 匿名变量)
|
||||||
|
// 2. 真正的 return 返回
|
||||||
|
// defer 执行的 时机是在 这两步之间
|
||||||
|
func demo() int {
|
||||||
|
x := 5
|
||||||
|
defer func() {
|
||||||
|
// 此处修改的是 x 不是 真正的 返回值
|
||||||
|
x++
|
||||||
|
}()
|
||||||
|
// 此时 x 已经赋值给返回值
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func demo2() (x int) {
|
||||||
|
defer func() {
|
||||||
|
// 返回值 x++ = 6
|
||||||
|
x++
|
||||||
|
}()
|
||||||
|
// 返回值 x 赋值为 5
|
||||||
|
return 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
res := demo()
|
||||||
|
fmt.Printf("demo => %T %+v\n", res, res)
|
||||||
|
|
||||||
|
res = demo2()
|
||||||
|
fmt.Printf("demo => %T %+v\n", res, res)
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user