首頁 > 後端開發 > Golang > 主體

將指標傳遞給 go defer 函數不起作用

WBOY
發布: 2024-02-13 12:24:09
轉載
638 人瀏覽過

将指针传递给 go defer 函数不起作用

在 PHP 程式設計中,指標傳遞給 go defer 函數時可能會出現不起作用的情況。 PHP 中的指針用於儲存變數的記憶體位址,透過傳遞指針,可以在函數內部修改原始變數的值。然而,當指標傳遞給 go defer 函數時,有時會出現無法修改原始變數的情況。這可能是由於 go defer 函數在執行時會建立新的 Goroutine,而指標可能指向了不同的記憶體空間,導致無法正確修改變數的值。因此,在 PHP 程式設計中,應謹慎使用指標傳遞給 go defer 函數,以避免出現意想不到的問題。

問題內容

在我的程式碼中,我嘗試使用 numaddr 來記錄 defer 語句後 num 的變化

func deferrun() {
    num := 1
    numaddr := &num
    defer fmt.printf("num is %d", *numaddr)
    num = 2
    return
}

func main() {
    deferrun()
}

登入後複製

但我得到 num 是 1 而不是 2,為什麼 defer 函數使用 *numaddr 的值而不是位址?

那我試試另一種方法

func deferRun() {
    num := 1
    numAddr := &num
    defer func(intAddr *int){
        fmt.Printf("num is %d", *numAddr)
    }(numAddr)
    
    num = 2
    fmt.Println("num is", *numAddr)
    return
}

func main() {
    deferRun()
}
登入後複製

這次它起作用了,我得到num 是2,所以我想也許defer fmt.printf(something) 在聲明它時立即儲存了字串,並且當defer 函數實際執行時沒有使用numaddr ?

解決方法

有趣的問題。要回答這個問題,你必須知道一個規則,就像這個 go 教學 https://go.dev/遊覽/流量控制/12

#延遲呼叫的參數會立即計算,但直到周圍函數返回時才會執行函數呼叫。

範例 1:告訴 defer 函數列印位於指定記憶體位址的值。

func deferrun() {
    num := 1
    numaddr := &num //address of variable num in stack memory, 0xc000076f38 for example
    defer func(intaddr *int){
        fmt.printf("num is %d", *numaddr)
    }(numaddr) //hey go, when the surrounding function returns, print the value located in this address (numaddr=0xc000076f38)
    num = 2 //now the value located in address 0xc000076f38 is 2
    return  
}
登入後複製

輸出將為 2。

範例 2:告訴 defer 函數列印指定的值。

func deferRun() {
    num := 1
    numAddr := &num //address of variable num in stack memory, 0xc000076f38 for example
    defer fmt.Printf("num is %d", *numAddr) //Hey Go, when the surrounding function returns, print the this value *numAddr (*numAddr is 1 for now)
    num = 2 //Now the value located in address 0xc000076f38 is 2 but you told the defer function to print 1 before
    return  
}
登入後複製

輸出將為 1。

以上是將指標傳遞給 go defer 函數不起作用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!