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 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型