title: Returning File Pointer in Golang
body: <p>I'm still struggling with the basics of Golang.</p>
  
  <p>Consider the following sample code:</p>
  
  <pre><code>func OpenOutputFile(name string) (fp *os.File) {
    fp, err := os.Create(name)
    if err != nil {
        panic(err)
    }
  
    defer func() {
        if err := fp.Close(); err != nil {
            panic(err)
        }
    }()
  
    return fp
  }
  </code></pre>
  
  <p>I would assume that calling:</p>
  
  <pre><code>fp := OpenOutputFile("output.txt")
  </code></pre>
  
  <p>would now make <code>fp</code> a file pointer (<code>*os.File</code>), so that I could call a statement like:</p>
  
  <pre><code>io.WriteString(fp, "Hello World")
  </code></pre>
  
  <p>In another function. But when calling this method, the error is generated:</p>
  
  <pre><code>0 write output.txt: bad file descriptor
  </code></pre>
  
  <p>So it appears that the pointer returned is not valid. How can I return a properly formed pointer to use with <code>io.WriteString</code>?</p>
  
  <p>I appreciate the help!</p>
  
  <p>Of note: Everything executes as intended when the creation of the file pointer and the writing to the file pointer exists in the same method. Breaking the logic into a function causes it to not behave as intended.</p>