From 16a819821ece9ad209402dd2b456ff9743436efb Mon Sep 17 00:00:00 2001 From: Shikong <919411476@qq.com> Date: Tue, 21 Sep 2021 01:29:22 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20Defer=20=E5=BB=B6=E6=97=B6=E6=89=A7?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base/function/defer/main.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 base/function/defer/main.go diff --git a/base/function/defer/main.go b/base/function/defer/main.go new file mode 100644 index 0000000..024b5f1 --- /dev/null +++ b/base/function/defer/main.go @@ -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) +}