如何在golang中关闭bufio.Reader / Writer?

时间:2012-11-22 12:20:31

标签: go

如何关闭golang中的bufio.Readerbufio.Writer

func init(){
    file,_ := os.Create("result.txt")
    writer = bufio.NewWriter(file)
}

我应该关闭Writer吗?或者只是使用file.Close()会使Writer关闭?

2 个答案:

答案 0 :(得分:19)

据我所知,您无法关闭bufio.Writer

您所做的是Flush() bufio.Writer然后Close() os.Writer

writer.Flush()
file.Close()

答案 1 :(得分:1)

我认为以下是规范性的:

func doSomething(filename string){
    file, err := os.Create(filename)
    // check err
    defer file.Close()
    writer = bufio.NewWriter(file)
    defer writer.Flush()

    // use writer here
}