panic 的场景:
- 数组或切片越界,例如
s := make([]int, 3); fmt.Println(s[5])
会引发 panic: runtime error: index out of range - 空指针调用,例如
var p *Person; fmt.Println(p.Name)
会引发 panic: runtime error: invalid memory address or nil pointer dereference - 过早关闭 HTTP 响应体,例如
resp, err := http.Get(url); defer resp.Body.Close(); if err != nil { return err }
会引发 panic: runtime error: invalid memory address or nil pointer dereference,因为如果 http.Get 出错,resp 可能是 nil - 除以零,例如
x := 0; y := 1 / x
会引发 panic: runtime error: integer divide by zero - 向已经关闭的 channel 发送或接收消息,例如
ch := make(chan int); close(ch); ch <- 1
会引发 panic: send on closed channel - 重复关闭 channel,例如
ch := make(chan int); close(ch); close(ch)
会引发 panic: close of closed channel - 关闭未初始化的 channel,例如
var ch chan int; close(ch)
会引发 panic: close of nil channel - 未初始化的 map,例如
var m map[string]int; m["key"] = 1
会引发 panic: assignment to entry in nil map