」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > `defer'語句如何根據變量聲明影響go中的返回值?

`defer'語句如何根據變量聲明影響go中的返回值?

發佈於2025-03-23
瀏覽:613

How Do `defer` Statements Affect Return Values in Go Based on Variable Declaration?
在Golang中使用defer

,由於i是輸入參數,返回值不受延遲增量的影響,導致print Outter輸出為0。

,i是命名的結果參數,其中返回值在返回值中已明確分配給IT,然後將其明確分配給IT,然後才能在遞延之前明確分配。 Thus, the deferred increment affects the returned value, giving an output of 1.However, in c2(), even though i is returned explicitly as 2, the deferred increment modifies the result parameter, resulting in a return value of 3.

The specification clarifies this behavior:

Return statements:

A "return" statement that指定結果設置結果參數在執行任何延遲函數之前。
func c(i int) int {
    defer func() { i   }()
    return i
}

func c1() (i int) {
    defer func() { i   }()
    return i
}

func c2() (i int) {
    defer func() { i   }()
    return 2
}
此原理都適用於函數和方法,在函數和方法中,延遲函數可以在返回之前訪問和修改命名的結果參數。因此,考慮可變聲明和延期函數修改如何影響最終返回值。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3