Chủ đề Go quan trọng
Go defer, panic and recover
Run cleanup code when a function returns, and turn a panic back into an ordinary error.
Bạn sẽ học được gì
- defer
- Deferred calls run in reverse
- recover
readConfig()
- 1
open fileruns first - 2
defer closescheduled - 3
read settingsruns second - 4
close 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.
Những điểm quan trọng
- A deferred call runs when the function returns.
- Several defers run last in, first out.
- recover catches a panic inside a deferred function.
Ví dụ Go chạy được
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))
}
open file
read settings
close file
5 <nil>
0 recovered: runtime error: integer divide by zero
deferred 3
deferred 2
deferred 1Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
Tất cả thử thách