Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

c01/c01_12 #41

Open
utterances-bot opened this issue May 31, 2022 · 6 comments
Open

c01/c01_12 #41

utterances-bot opened this issue May 31, 2022 · 6 comments

Comments

@utterances-bot
Copy link

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

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

Copy link

TYtrack commented May 31, 2022

defer在return后调用

Copy link

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

Copy link

有点像python 中 finanly的用法

Copy link

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

Copy link

wuxinlei commented Feb 8, 2023

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

Copy link

/**

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants