Skip to content

Instantly share code, notes, and snippets.

@JesseYan
Last active August 24, 2018 08:26
Show Gist options
  • Save JesseYan/fdcf172b08ad4b7c023d21b2130eaadb to your computer and use it in GitHub Desktop.
Save JesseYan/fdcf172b08ad4b7c023d21b2130eaadb to your computer and use it in GitHub Desktop.
defer和panic的用法,注意点

defer和panic怎么合用?

if v.IndicatorType == IndicatorTypeCalc {
	func() {
		defer func() {
			if err := recover(); nil != err {
				fmt.Printf("\n$$$$$$ indicator [%v](data_model_id:[%v]) analyze failed:%v", v.Name, v.DataModelID, err)
			}
		}()
		v.ConvertExpr = m.convertCalcExprToCommonExpr(v.Expr, 0)
		v.CompositionCommonIndicator = m.parseCalculateExprToCommonIndicators(v.Expr)
	}()
}

defer的用法

package main

import "fmt"

func deferFunc() int {
	index := 0

	fc := func() {

		fmt.Println(index, "匿名函数1")
		index++

		defer func() {
			fmt.Println(index, "匿名函数1-1")
			index++
		}()
	}

	defer func() {
		fmt.Println(index, "匿名函数2")
		index++
	}()

	defer fc()

	return func() int {
		fmt.Println(index, "匿名函数3")
		index++
		return index
	}()
}

func main() {
	result := deferFunc()
	fmt.Println(result, "main函数")
}

输出

0 匿名函数3
1 匿名函数1
2 匿名函数1-1
3 匿名函数2
1 main函数

延迟执行,在声明时不会立即执行,而是在函数return后时按照后进先出的原则依次执行每一个defer。这样带来的好处是,能确保我们定义的函数能百分之百能够被执行到,这样就能做很多我们想做的事,如释放资源,清理数据,记录日志等

有如下结论:

  • defer 是在执行完return 后执行
  • defer 后进先执行
file , err :=os.Open(file)
if err != nil {
    return err
}
defer file.Close() 
//dosomething with file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment