3 回答

TA貢獻1872條經驗 獲得超4個贊
defer 語句將函數調用推送到列表中。保存的調用列表在周圍函數返回后執行。-- Go 博客:延遲、恐慌和恢復
理解上述語句的另一種方式:
defer 語句將函數調用壓入堆棧。彈出的已保存調用堆棧(LIFO)和延遲函數在周圍函數返回之前立即調用。
func c() (i int) {
defer func() { i++ }()
return 1
}
返回 1 后,func() { i++ }()執行延遲。因此,按照執行順序:
i = 1(返回 1)
i++(延遲函數從堆棧中彈出并執行)
i == 2(命名變量 i 的最終結果)
為了理解起見:
func c() (i int) {
defer func() { fmt.Println("third") }()
defer func() { fmt.Println("second") }()
defer func() { fmt.Println("first") }()
return 1
}
執行順序:
i = 1(返回 1)
“第一的”
“第二”
“第三”

TA貢獻1817條經驗 獲得超14個贊
我認為混淆是關于功能中的功能,如果你這樣分類:
func main() {
fmt.Println(c()) //the result is 5
}
// the c function returned value is named j
func c() (j int) {
defer changei(&j)
return 6
}
func changei(j *int) {
//now j is 6 because it was assigned by return statement
// and if i change guess what?! i changed the returned value
*j--;
}
但是如果返回值不是這樣命名的:
func main() {
fmt.Println(c()) //the result will become 6
}
// the c function returned value is not named at this time
func c() int {
j := 1
defer changei(&j)
return 6
}
func changei(j *int) {
//now j = 1
// and if i change guess what?! it will not effects the returned value
*j--;
}
我希望這能消除混亂,這就是我快樂 Go 編碼的方式
- 3 回答
- 0 關注
- 239 瀏覽
添加回答
舉報