doujiexi1824 2015-02-02 13:45
浏览 48
已采纳

对指针使用延迟

Let us say that I have the following code:

func getConnection(fileName string) *os.File {
    file, err := os.Open(fileName)
    //Check for error
    return file
}

I use this function to open a file and the function is called from another function that does some other activity.

My question is, now that I have opened the file, how do I close it. If I were to add defer file.Close() inside getConnection(), wouldn't it close the file before returning? Does it make sense to use defer inside the calling function?

  • 写回答

1条回答 默认 最新

  • dtziv24262 2015-02-02 13:50
    关注

    If the purpose of your function is to return a file, why would you want to close it in the function that returns it?

    In this case it is the responsibility of the caller to properly close the file, preferably with defer:

    func usingGetConnection() {
        f := getConnection("file.txt")
        defer f.Close()
        // Use f here
    }
    

    Although your getConnection() function swallows errors, you should use multi-return value to indicate problems like this:

    func getConnection(fileName string) (*os.File, error) {
        file, err := os.Open(fileName)
        //Check for error
        if err != nil {
            return nil, err
        }
        return file, nil
    }
    

    And using it:

    func usingGetConnection() {
        f, err := getConnection("file.txt")
        if err != nil {
            panic(err) // Handle err somehow
        }
        defer f.Close()
        // Use f here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line