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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵