🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
> # 片段一 defer - pannic 和defer打印顺序 : pannic 后终止后续代码执行, 按后进先出顺序打印defer最后再打印pannic ``` package main import "fmt" func main() { defer func() { fmt.Println("1111") }() defer func() { fmt.Println("2222") }() defer func() { fmt.Println("3333") }() panic("4444") } ``` --- - defer 多个函数时只对最后一个生效 ~~~ package main import "fmt" type Slice []int func NewSlice() Slice { return make(Slice, 0) } func (s *Slice) Add(elem int) *Slice { *s = append(*s, elem) fmt.Println(elem) return s } func main() { s := NewSlice() defer s.Add(1).Add(2) s.Add(3) } ~~~ ~~~ package main //https://blog.golang.org/defer-panic-and-recover import "fmt" func main() { f() fmt.Println("Returned normally from f.") } func f() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered in f", r) } }() fmt.Println("Calling g.") g(0) fmt.Println("Returned normally from g.") } func g(i int) { if i > 3 { fmt.Println("Panicking!") panic(1) //panic 中止了当前函数,逐级回溯直至在 defer 中遇到 recover 后恢复。 } defer fmt.Println("Defer in g", i) fmt.Println("Printing in g", i) g(i + 1) } ~~~ - return 返回值 ~~~ func main() { fmt.Println(ddd()) } func ddd() string { defer fmt.Println("999") defer ccc() return "ddd" } func ccc() string { fmt.Println("ccc") return "" } ~~~