หัวข้อสำคัญของ Go

Go defer, panic and recover

Run cleanup code when a function returns, and turn a panic back into an ordinary error.

  • ระดับกลาง
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • defer
  • Deferred calls run in reverse
  • recover
readConfig()
  1. 1open fileruns first
  2. 2defer closescheduled
  3. 3read settingsruns second
  4. 4close fileruns on return

Cleanup that always runs

defer schedules a call to run when the surrounding function returns, which makes it the usual way to close files and release locks. A panic stops the normal flow, and recover, called in a deferred function, catches it.

close file prints after read settings because the deferred call runs when readConfig returns. Dividing by zero panics; the deferred function recovers and stores an error in the named result err. The three deferred calls in main run last, in reverse order.

ประเด็นสำคัญ

  1. A deferred call runs when the function returns.
  2. Several defers run last in, first out.
  3. recover catches a panic inside a deferred function.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import "fmt"

func readConfig() {
	fmt.Println("open file")
	defer fmt.Println("close file") // runs when the function returns
	fmt.Println("read settings")
}

func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

func main() {
	readConfig()

	for i := 1; i <= 3; i++ {
		defer fmt.Println("deferred", i) // last in, first out
	}

	fmt.Println(safeDivide(10, 2))
	fmt.Println(safeDivide(1, 0))
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
open file
read settings
close file
5 <nil>
0 recovered: runtime error: integer divide by zero
deferred 3
deferred 2
deferred 1

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Closures and Function Values →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด