简体   繁体   中英

How can I close bufio.Reader/Writer in golang?

How can I close bufio.Reader or bufio.Writer in golang?

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

Should I close Writer ? or just use file.Close() will make Writer close?

As far as I know, you can't close the bufio.Writer .

What you do is to Flush() the bufio.Writer and then Close() the os.Writer :

writer.Flush()
file.Close()

I think the following is canonical:

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

    // use writer here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM