切片越界
func main() {
// 捕捉异样
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
//panic 1.切片越界,上面的会panic!
arr := make([]int, 2)
arr[2] = 5
fmt.Println(arr)
}
运行后果
runtime error: index out of range [2] with length 2
反复敞开chan
func main() {
//2.反复敞开 chan
c := make(chan int)
close(c)
close(c)
}
运行后果
panic: close of closed channel
曾经敞开的chan持续发送
func main() {
//3.曾经敞开的chan 持续发送数据
d := make(chan int)
close(d)
d <- 1
}
运行后果
panic: send on closed channel
空指针的状况,定义的指针变量没有初始化,就间接应用
func main() {
//4.空指针的状况,定义的指针变量没有初始化,就间接应用
var p *people
fmt.Println(p.printName)
}
type people struct {
Name string
Age int
}
func (p people) printName() {
fmt.Println(p.Name)
}
运行后果
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x12cb491]
定义的map没有初始化就间接应用
func main(){
//5. map 没有初始化间接应用
var m map[int]string
m[0] = "111"
}
运行后果
panic: assignment to entry in nil map
常见的谬误然而不是panic的状况
数组越界 在程序运行就爆红了
多个groutine 读写 map
func main() {
//多个groutine 读写 map, 产生 fatal error: concurrent map writes, 而不是 panic
m := make(map[int]string)
go func() {
m[1] = "111"
}()
go func() {
m[1] = "111"
}()
fmt.Println(m)
运行后果
fatal error: concurrent map writes
发表回复