GolangCodingTime
GolangCodingTime copied to clipboard
c01/c01_12
defer在return后调用
我们知道在 Python 中可以使用 defer 实现对资源的管理
是 with 吧
有点像python 中 finanly的用法
并非defer在return后调用 return不是原子性操作,1先复制 2在调用ret指令,而defer就在 这 1 2之间,不相信的话 使用下具名函数试试: func test()(x int) { x = 10 defer func() { x++ }() return x }
defer和return涉及到一个具名参数问题,先赋值返回值,然后defer,最后return
/**
- Java 代码释放资源try-catch-finally */ try(// get resouece of os or db and so on..){ // do some operations }catch(Exception ex){ ex.printStackTrace(); } finally { // resource release method. }
// go 版本 func method( ) int{ // get resource of os or db.. writer = os.openFile(...) // release resource defer writer.close()
// other operations var a int = xxx() return a }