iswbm / GolangCodingTime

Go编程时光,一个零基础入门 Golang 的教程

Home Page:http://golang.iswbm.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

c01/c01_12

utterances-bot opened this issue · comments

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

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

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
}