dtgu21994537 2016-03-20 03:22
浏览 296
已采纳

在Golang中返回文件指针

I'm still struggling with the basics of Golang.

Consider the following sample 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
}

I would assume that calling:

fp := OpenOutputFile("output.txt")

would now make fp a file pointer (*os.File), so that I could call a statement like:

io.WriteString(fp, "Hello World")

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

0 write output.txt: bad file descriptor

So it appears that the pointer returned is not valid. How can I return a properly formed pointer to use with io.WriteString?

I appreciate the help!

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.

  • 写回答

1条回答 默认 最新

  • douba1067 2016-03-20 03:27
    关注

    The Go Programming Language Specification

    Defer statements

    A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

    Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred. If a deferred function value evaluates to nil, execution panics when the function is invoked, not when the "defer" statement is executed.

    For instance, if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. If the deferred function has any return values, they are discarded when the function completes.

    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
    }
    

    You open the file

    fp, err := os.Create(name)
    

    You close the file

    err := fp.Close()
    

    After the Close, fp no longer points to a valid file descriptor.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 汇川EASY521plc电子凸轮
  • ¥15 C++ 如何判断设置快捷键来实现隐藏/显示窗口
  • ¥15 关于#材料工程#的问题:有没有具有电子阻挡层和空穴阻挡层的电池仿真silvaco代码例子或者其他器件具有阻挡层例子的silvaco代码(最好还有相关文献)
  • ¥60 基于MATLAB的TAOD算法
  • ¥15 Groimp使用疑问
  • ¥15 MDK–ARM里一直找不到调试器
  • ¥15 oracle中sql查询问题
  • ¥15 vue使用gojs3.0版本,在nodeDataArray中的iconSrc使用gif本地路径,展示出来后动画是静态的,不是动态的
  • ¥100 代写个MATLAB代码,有偿
  • ¥15 ansys electronics 2021 R1安装报错,错误代码2,如图