go 学习笔记之咬文嚼字带你弄清楚 defer 延迟函数
温故知新不忘延迟基础 A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking. 延迟函数的 运行时机 一般有三种情况: 周围函数遇到返回时 func funcWithMultipleDeferAndReturn() { defer fmt.Println(1) defer fmt.Println(2) fmt.Println(3) return fmt.Println(4) } 运行结果: 3 2 1 . 「雪之梦技术驿站」: defer fmt.Println(1) 和 defer fmt.Println(2) 两个语句由于前面存在 defer 关键字,因此均 被延迟 到正常语句 return 前.当多个 defer 语句均被延迟时,倒序执行延迟语句,这种特点非常类似于数据结构的 栈 (先入后出)