title: Deferring deferrements in Golang
body: <p>I'm new to Go and I have to write an app which has to open lots of files at various points. The code to open each file would be</p>
  
  <pre><code>fl, err := os.Open(..)
  check(err)
  defer fl.Close()
  </code></pre>
  
  <p>where <code>check</code> simply calls <code>panic</code> if anything goes wrong.</p>
  
  <p>Now, as I said, that snippet repeats itself quite a few times. I'd like to have something like this:</p>
  
  <pre><code>func foo(f string){
      fl, err := os.Open(f)
      check(err)
      defer fl.Close() //lolwut
  }
  </code></pre>
  
  <p>Of course once <code>foo</code> returns, <code>defer</code> would kick in and close the file.</p>
  
  <p>Is there a way to <em>defer</em> deferrements for a function until its caller decides it's time?</p>
  
  <p>What I've tried to do so far is, put the defer in an anonymous function, have <code>foo</code> return it and have the caller execute <em>that</em> (preferably in a one-liner). Yet I'm hitting some obstacles implementing that and I'm not even sure if it's the correct approach.</p>
  
  <p><strong>tl;dr:</strong> Is there a way to defer deferrements to the calling function in Go?</p>