Return file pointer in Golang

I am still struggling with the basics of the Golang.

Consider the following code example:

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
}

I would suggest that the call:

fp := OpenOutputFile("output.txt")

will now do fpa file pointer ( *os.File) so that I can call an operator like:

io.WriteString(fp, "Hello World")

In another function. But when calling this method, an error is generated:

0 write output.txt: bad file descriptor

Thus, it seems that the returned pointer is invalid. How can I return a properly formed pointer for use with io.WriteString?

I appreciate the help!

Note. Everything is done as intended when creating a file pointer and writing to a file pointer exists in the same method. Interrupting logic in a function causes it to not behave as intended.

+4
source share
1

Go

"" , , , , , return, , .

, "defer", , . . nil, , "defer".

, , , . , , .

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
}

fp, err := os.Create(name)

err := fp.Close()

Close, fp .

+3

All Articles