duanjie6912 2016-05-21 13:40
浏览 39
已采纳

我们可以像在python中一样在Go中创建上下文管理器吗

In python, I find the context managers really helpful. I was trying to find the same in Go.

e.g:

  1. with open("filename") as f:
  2. do something here

where open is a context manager in python handling the entry and exit, which implicitly takes care of closing the file opened.

Instead of we explicitly doing like this:

  1. f := os.Open("filename")
  2. //do something here
  3. defer f.Close()

Can this be done in Go as well ? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongyi1921 2016-05-21 13:43
    关注

    No, you can't, but you can create the same illusion with a little wrapper func:

    1. func WithFile(fname string, fn func(f *os.File) error) error {
    2. f, err := os.Open(fname)
    3. if err != nil {
    4. return err
    5. }
    6. defer f.Close()
    7. return fn(f)
    8. }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部