在Golang中使用defer
,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