GolangCodingTime icon indicating copy to clipboard operation
GolangCodingTime copied to clipboard

c01/c01_12

Open utterances-bot opened this issue 3 years ago • 6 comments

1.12 流程控制:defer 延迟语句 — Go编程时光 1.0.0 documentation

https://golang.iswbm.com/c01/c01_12.html

utterances-bot avatar May 31 '22 07:05 utterances-bot

defer在return后调用

TYtrack avatar May 31 '22 07:05 TYtrack

我们知道在 Python 中可以使用 defer 实现对资源的管理 是 with 吧

green961 avatar Aug 25 '22 14:08 green961

有点像python 中 finanly的用法

ShawnQiang1 avatar Oct 14 '22 11:10 ShawnQiang1

并非defer在return后调用 return不是原子性操作,1先复制 2在调用ret指令,而defer就在 这 1 2之间,不相信的话 使用下具名函数试试: func test()(x int) { x = 10 defer func() { x++ }() return x }

gogohead avatar Dec 19 '22 10:12 gogohead

defer和return涉及到一个具名参数问题,先赋值返回值,然后defer,最后return

wuxinlei avatar Feb 08 '23 07:02 wuxinlei

/**

  • 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 }

lekuyuan avatar Jul 03 '23 06:07 lekuyuan