[ Go ] 8. defer

defer fmt.Println(“結束惹”)

Artis Tu
Artis Tu
Sep 7, 2018 · 1 min read

defer 可以使函式延遲至 return 前執行,範例如下:

輸出為: World Hello

可以發現 Hello 在 World 之前就輸出了。


defer 的函式會被丟到一個 stack 中,在 return 前才執行,因此它是 LIFO,依照被 defer 的順序反過來執行

輸出為: 9 8 7 6 5 4 3 2 1 0


Artis 的程式學習筆記

Artis Tu

Written by

Artis Tu

Artis 的程式學習筆記

記錄日常所學

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade