Go基础学习

A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

defer延迟
用法:1.对象.close(),临时文件的删除
   2.关于异常的处理,使用panic()和recover()
panic函数用于引发恐慌,导致程序中断执行
recover函数用于恢复程序的执行,recover()语法上要求必须在defer中执行。

多个defer函数 栈的结构 lifo 后进先出
defer函数调用时已经传递参数数据了,只是暂时不执行函数中的代码。
defer函数注意点:
1.当外围函数中的语句正常执行完毕时,只有其中所有的延迟函数都执行完毕,外围函数才会真正的结束执行。
2.当执行外围函数中的return语句时,只有其中所有的延迟函数都执行完毕后,外围函数才会真正返回。
3.当外围函数中的代码引发运行恐慌时,只有其中的延迟函数都执行完毕后,该运行时恐慌才会真正被扩展至调用函数。

猜你喜欢

转载自www.cnblogs.com/akmfwei/p/12603015.html