搜尋
首頁後端開發GolangGolang Defer:堆疊分配、堆疊分配、開放式編碼的 Defer

這是帖子的摘錄;完整的帖子可以在這裡找到:Golang Defer:從基礎到陷阱。

defer 語句可能是我們開始學習 Go 時首先發現非常有趣的事情之一,對吧?

但是它還有很多讓很多人困惑的地方,並且有許多令人著迷的方面是我們在使用它時經常沒有觸及的。

Golang Defer: Heap-allocated, Stack-allocated, Open-coded Defer

堆疊分配、堆疊分配、開放式編碼延遲

例如,defer 語句實際上有 3 種類型(從 Go 1.22 開始,儘管以後可能會改變):開放編碼 defer、堆疊分配 defer 和堆疊分配。每一種都有不同的效能和不同的最佳使用場景,如果您想優化效能,了解這一點很有幫助。

在本次討論中,我們將涵蓋從基礎知識到更高級用法的所有內容,我們甚至會深入研究一些內部細節。

什麼是延期?

在我們深入探討之前,讓我們先快速瀏覽一下 defer。

在 Go 中,defer 是一個關鍵字,用於延遲函數的執行,直到周圍的函數完成。

func main() {
  defer fmt.Println("hello")
  fmt.Println("world")
}

// Output:
// world
// hello

在此程式碼片段中,defer 語句安排 fmt.Println("hello") 在 main 函數的最後執行。因此,立即呼叫 fmt.Println("world"),並先列印「world」。之後,因為我們使用了 defer,所以在 main 完成之前的最後一步會列印「hello」。

這就像設定一個任務稍後運行,就在函數退出之前。這對於清理作業非常有用,例如關閉資料庫連線、釋放互斥體或關閉檔案:

func doSomething() error {
  f, err := os.Open("phuong-secrets.txt")
  if err != nil {
    return err
  }
  defer f.Close()

  // ...
}

上面的程式碼是展示 defer 如何運作的一個很好的例子,但這也是一個糟糕的使用 defer 的方式。我們將在下一節中討論這個問題。

「好吧,很好,但為什麼不把 f.Close() 放在最後呢?」

這樣做有幾個很好的理由:

  • 我們將關閉操作放在開啟附近,這樣更容易遵循邏輯並避免忘記關閉文件。我不想向下滾動函數來檢查文件是否已關閉;它分散了我對主要邏輯的注意力。
  • 即使發生恐慌(運行時錯誤),延遲函數也會在函數返回時被呼叫。

當發生恐慌時,堆疊將被展開,並且延遲函數將按特定順序執行,我們將在下一節中介紹。

延遲堆積

當您在函數中使用多個 defer 語句時,它們會按「堆疊」順序執行,這表示最後一個延遲函數會先執行。

func main() {
  defer fmt.Println(1)
  defer fmt.Println(2)
  defer fmt.Println(3)
}

// Output:
// 3
// 2
// 1

每次呼叫 defer 語句時,都會將此函數加入到目前 goroutine 鍊錶的頂部,如下所示:

Golang Defer: Heap-allocated, Stack-allocated, Open-coded Defer

Goroutine 延遲鏈

當函數傳回時,它會遍歷鍊錶並按照上圖所示的順序執行每個鍊錶。

但請記住,它不會執行 goroutine 鍊錶中的所有 defer,它只運行返回函數中的 defer,因為我們的 defer 鍊錶可能包含來自許多不同函數的許多 defer。

func B() {
  defer fmt.Println(1)
  defer fmt.Println(2)
  A()
}

func A() {
  defer fmt.Println(3)
  defer fmt.Println(4)
}

因此,僅執行目前函數(或目前堆疊幀)中的延遲函數。

Golang Defer: Heap-allocated, Stack-allocated, Open-coded Defer

Goroutine 延遲鏈

但是有一個典型情況,當前 goroutine 中的所有延遲函數都被追蹤並執行,那就是發生恐慌的時候。

延遲、恐慌和恢復

除了編譯時錯誤之外,我們還有很多執行時間錯誤:除以零(僅限整數)、越界、取消引用 nil 指標等等。這些錯誤會導致應用程式出現恐慌。

Panic 是一種停止當前 goroutine 執行、展開堆疊並執行當前 goroutine 中的延遲函數的方法,從而導致我們的應用程式崩潰。

為了處理意外錯誤並防止應用程式崩潰,您可以在延遲函數中使用復原函數來重新獲得對恐慌 goroutine 的控制。

func main() {
  defer func() {
    if r := recover(); r != nil {
      fmt.Println("Recovered:", r)
    }
  }()

  panic("This is a panic")
}

// Output:
// Recovered: This is a panic

通常,人們在恐慌中放入錯誤並使用recover(..)捕獲該錯誤,但它可以是任何東西:字串、整數等。

In the example above, inside the deferred function is the only place you can use recover. Let me explain this a bit more.

There are a couple of mistakes we could list here. I’ve seen at least three snippets like this in real code.

The first one is, using recover directly as a deferred function:

func main() {
  defer recover()

  panic("This is a panic")
}

The code above still panics, and this is by design of the Go runtime.

The recover function is meant to catch a panic, but it has to be called within a deferred function to work properly.

Behind the scenes, our call to recover is actually the runtime.gorecover, and it checks that the recover call is happening in the right context, specifically from the correct deferred function that was active when the panic occurred.

"Does that mean we can’t use recover in a function inside a deferred function, like this?"

func myRecover() {
  if r := recover(); r != nil {
    fmt.Println("Recovered:", r)
  }
}

func main() {
  defer func() {
    myRecover()
    // ...
  }()

  panic("This is a panic")
}

Exactly, the code above won’t work as you might expect. That’s because recover isn’t called directly from a deferred function but from a nested function.

Now, another mistake is trying to catch a panic from a different goroutine:

func main() {
  defer func() {
    if r := recover(); r != nil {
      fmt.Println("Recovered:", r)
    }
  }()

  go panic("This is a panic")

  time.Sleep(1 * time.Second) // Wait for the goroutine to finish
}

Makes sense, right? We already know that defer chains belong to a specific goroutine. It would be tough if one goroutine could intervene in another to handle the panic since each goroutine has its own stack.

Unfortunately, the only way out in this case is crashing the application if we don’t handle the panic in that goroutine.

Defer arguments, including receiver are immediately evaluated

I've run into this problem before, where old data got pushed to the analytics system, and it was tough to figure out why.

Here’s what I mean:

func pushAnalytic(a int) {
  fmt.Println(a)
}

func main() {
  a := 10
  defer pushAnalytic(a)

  a = 20
}

What do you think the output will be? It's 10, not 20.

That's because when you use the defer statement, it grabs the values right then. This is called "capture by value." So, the value of a that gets sent to pushAnalytic is set to 10 when the defer is scheduled, even though a changes later.

There are two ways to fix this.

...

Full post is available here: Golang Defer: From Basic To Trap.

以上是Golang Defer:堆疊分配、堆疊分配、開放式編碼的 Defer的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Golang:Go編程語言解釋了Golang:Go編程語言解釋了Apr 10, 2025 am 11:18 AM

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Golang的目的:建立高效且可擴展的系統Golang的目的:建立高效且可擴展的系統Apr 09, 2025 pm 05:17 PM

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

SQL排序中ORDER BY語句結果為何有時看似隨機?SQL排序中ORDER BY語句結果為何有時看似隨機?Apr 02, 2025 pm 05:24 PM

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

技術棧收斂是否僅僅是技術棧選型的過程?技術棧收斂是否僅僅是技術棧選型的過程?Apr 02, 2025 pm 05:21 PM

技術棧收斂與技術選型的關係在軟件開發中,技術棧的選擇和管理是一個非常關鍵的問題。最近,有讀者提出了...

如何在Go語言中使用反射對比並處理三個結構體的差異?如何在Go語言中使用反射對比並處理三個結構體的差異?Apr 02, 2025 pm 05:15 PM

Go語言中如何對比並處理三個結構體在Go語言編程中,有時需要對比兩個結構體的差異,並將這些差異應用到第�...

在Go語言中如何查看全局安裝的包?在Go語言中如何查看全局安裝的包?Apr 02, 2025 pm 05:12 PM

在Go語言中如何查看全局安裝的包?在使用Go語言開發過程中,經常會使用go...

GoLand中自定義結構體標籤不顯示怎麼辦?GoLand中自定義結構體標籤不顯示怎麼辦?Apr 02, 2025 pm 05:09 PM

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中