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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?