我可以创建一个只能与 defer 一起使用的函数吗?

例如:


package package


// Dear user, CleanUp must only be used with defer: defer CleanUp()

func CleanUp() {

    // some logic to check if call was deferred

    // do tear down

}

在用户空间代码中:


func main() {

    package.CleanUp() // PANIC, CleanUp must be deferred!

}

但是如果用户运行,一切都应该没问题:


func main() {

   defer package.CleanUp() // good job, no panic

}

我已经尝试过的事情:


func DeferCleanUp() {

    defer func() { /* do tear down */ }()

    // But then I realized this was exactly the opposite of what I needed

    // user doesn't need to call defer CleanUp anymore but...

}

// now if the APi is misused it can cause problems too:

defer DeferCleanUp() // a defer inception xD, question remains.


茅侃侃
浏览 147回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go