github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/20_trap/deferfunc/demo1.go (about)

     1  package main
     2  
     3  import "fmt"
     4  
     5  func deferFunReturn() (result int) {
     6  	i := 0
     7  	defer func() {
     8  		//i++ // 不会改变返回值
     9  		result++ // 会改变返回值  延迟函数可能操作主函数的具名返回
    10  	}()
    11  	return i
    12  }
    13  
    14  func deferFunReturn2() int {
    15  	i := 0
    16  	defer func() {
    17  		i++ // 不会改变返回值
    18  	}()
    19  	return i
    20  }
    21  
    22  func main() {
    23  	fmt.Println(deferFunReturn())
    24  	fmt.Println(deferFunReturn2())
    25  	go Dived(0)
    26  
    27  	//Dived2(0) // 会 panic
    28  
    29  }
    30  
    31  func NoPanic() {
    32  	if err := recover(); err != nil {
    33  		fmt.Println("Recover success...")
    34  	}
    35  }
    36  
    37  func Dived2(n int) {
    38  	/*
    39  	   以下三个条件会让recover()返回nil:
    40  	   1. panic时指定的参数为nil;(一般panic语句如panic("xxx failed..."))
    41  	   2. 当前协程没有发生panic;
    42  	   3. recover没有被defer方法直接调用
    43  	*/
    44  	defer func() {
    45  		NoPanic() // 将会失败
    46  	}()
    47  
    48  	fmt.Println(1 / n)
    49  }
    50  
    51  func Dived(n int) {
    52  	defer NoPanic()
    53  
    54  	fmt.Println(1 / n)
    55  }