kkdai / blog

This is blog comment repo for https://www.evanlin.com/
0 stars 0 forks source link

golang-know-using-defer/ #56

Open kkdai opened 3 years ago

kkdai commented 3 years ago

[Golang] 相當好用但又要注意的Defer

http://www.evanlin.com/golang-know-using-defer/

kkdai commented 3 years ago

comment written by 許煜廷, created at 14 Sep 20 08:31 UTC,

印象中 `defer` 應該是在return後才執行!?

package main

import (
"fmt"
)

func main() {
fmt.Println(num()) // 1
}

func num() (a int) {
defer func() { a = 1 }()
return 2
}

kkdai commented 3 years ago

comment written by Polaris, created at 06 Nov 20 03:53 UTC,

或者說可不可以理解爲return之前就已經執行了,將a修正為2了呢?是最後return的1,而不是return之後才修正為1