英文:
How can I close bufio.Reader/Writer in golang?
问题
我应该如何关闭bufio.Reader
或bufio.Writer
在golang中?
func init(){
file,_ := os.Create("result.txt")
writer = bufio.NewWriter(file)
}
我应该关闭Writer
吗?还是只需要使用file.Close()
就会关闭Writer
?
英文:
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?
答案1
得分: 23
据我所知,你不能关闭bufio.Writer
。
你需要做的是先调用Flush()
方法刷新bufio.Writer
,然后再调用Close()
方法关闭os.Writer
:
writer.Flush()
file.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()
答案2
得分: 3
我认为以下是规范的:
func doSomething(filename string){
file, err := os.Create(filename)
// 检查错误
defer file.Close()
writer = bufio.NewWriter(file)
defer writer.Flush()
// 在这里使用 writer
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论