为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
茅侃侃 2021-09-10 15:18:26
例如: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.
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 146 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信