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() make Writer close?

+11
go
source share
2 answers

As far as I know, you cannot close bufio.Writer .

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

 writer.Flush() file.Close() 
+18
source share

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 } 
+1
source share

All Articles