当前位置:网站首页>Instructions for go defer

Instructions for go defer

2022-07-04 23:26:00 Yard farmer is by my side

defer yes go A deferred invocation mechanism in ,defer The following functions can only be executed after the current function is executed , Usually used to free up resources .
defer Follow the principle of first in, then out , Similar to the stack structure .
Why do we have to defer Designed into this mechanism ?
Because the resources applied later and may depend on the resources applied earlier . If the previously applied resources are released first . It may have an impact on later resources . So the resources released first and then applied for , Then release the resources previously applied for

func main() {

	defer func() {
		fmt.Println("w")
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()
	f()



}
func f() {
	fmt.Println("a")
	panic("error defer")
}


原网站

版权声明
本文为[Yard farmer is by my side]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041942036064.html