Go: defer與return小記

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

1 官方定義

A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.
defer運算式將一個函數調用儲存在列表中,當包裹defer的函數"返回"後,列表中的調用會被執行。defer通常用於清理收尾工作。
注意:這裡的返回加了引號,原因如下

2 實現邏輯

參考 雨痕大神的讀書筆記(https://github.com/qyuhen/book)源碼第20章
大致表達為:
step 1 : 在defer運算式的地方,會調用runtime.deferproc(size int32, fn *funcval)儲存延時調用,注意這裡儲存了延時調用的參數
step 2 : 在return時,先將傳回值儲存起來
step 3 : 按FILO順序調用runtime.deferreturn,即延時調用
step 4 : RET指令

因此,return並不是一個原子操作,函數傳回值可能與你的預期不一樣。

3 避坑提示

1. defer的參數在聲明時即被確定下來,先看個例子(生產環境這樣寫估計會被唾沫噴死)
func calc(index string, a, b int) int {    ret := a + b    fmt.Println(index, a, b, ret)    return ret}func main() {    a := 1    b := 2    defer calc("1", a, calc("10", a, b))    a = 0    defer calc("2", a, calc("20", a, b))    b = 1}

輸出結果為:

10 1 2 320 0 2 22 0 2 21 1 3 4

原因是defer calc("1", a, calc("10", a, b)) 的第3個參數會在調用runtime.deferproc時確定,並不會在延時調用時才會被計算。

2. 有名與無名傳回值
func namedReturn() (r int) {    defer func() {        r++        fmt.Println("defer in namedReturn : r = ", r)    }()    return}func unnamedReturn() int {    var r int    defer func() {        r++        fmt.Println("defer in unnamedReturn : r = ", r)    }()    return r}func main() {    fmt.Println("namedReturn : r = ", namedReturn())    fmt.Println("unnamedReturn : r = ", unnamedReturn())}

輸出結果為:

defer in namedReturn : r =  1namedReturn : r =  1defer in unnamedReturn : r =  1unnamedReturn : r =  0

原因就是return會將傳回值先儲存起來,對於無名傳回值來說,儲存在一個臨時對象中,defer是看不到這個臨時對象的;而對於有名傳回值來說,就儲存在已命名的變數中。

3. 延時參數與有名傳回值遮蔽
func ShelteredReturn() (r int) {    defer func(r int) {        r++        fmt.Println("defer in ShelteredReturn : r = ", r)    }(r)    return 0}func main() {    fmt.Println("ShelteredReturn : r = ", ShelteredReturn())}

輸出結果為:

defer in ShelteredReturn : r =  1ShelteredReturn : r =  0

雖然r是有名傳回值,但在defer func(r int)中的r是形參,與ShelteredReturn的傳回值不是同一個。

參考文獻

[1]. http://lib.csdn.net/article/go/33950
[2]. https://blog.golang.org/defer-panic-and-recover
[3]. https://my.oschina.net/henrylee2cn/blog/505535
[4]. https://github.com/qyuhen/book

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.