Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create context managers in Go like how we have in python

Tags:

go

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

e.g:

with open("filename") as f:
    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:

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

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

like image 232
chinmay Avatar asked Oct 24 '25 15:10

chinmay


1 Answers

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

func WithFile(fname string, fn func(f *os.File) error) error {
    f, err := os.Open(fname)
    if err != nil {
        return err
    }
    defer f.Close()
    return fn(f)
}
like image 153
OneOfOne Avatar answered Oct 27 '25 10:10

OneOfOne