Why Flush() or Close() methods are not cascading for Writers ?

357 views
Skip to first unread message

nicolas riesch

unread,
Dec 1, 2015, 3:56:01 PM12/1/15
to golang-nuts
In this little example, three Writers are chained.

   transform.Writer -> bufio.Writer -> os.File


When I want to close the Writers, I must:
  - close the transform.Writer
  - flush the bufio.Writer
  - close the os.File

I just wondered why Flush and Close don't "cascade" down the chain.
That is, calling Close on transform.Writer should call Flush on bufio.Writer, which would call Close on os.File.

It seems to me that the abstraction of io.WriteCloser is leaky, as the underlying Writer must be flushed and closed explicitely.
Have I missed some explanation ?


Jakob Borg

unread,
Dec 1, 2015, 4:03:07 PM12/1/15
to nicolas riesch, golang-nuts
On 1 dec. 2015, at 21:56, nicolas riesch <nicolas...@gmail.com> wrote:
>
> Flush on bufio.Writer, which would call Close on os.File.

You may want to write more than one thing to the file, or network socket, or whatever. Especially for sockets you may want to flush for each "message".

//jb
Message has been deleted

Uli Kunitz

unread,
Dec 1, 2015, 6:01:36 PM12/1/15
to golang-nuts
The reason is simple: You don't want Flush or Close to cascade down in every case. For instance you may want to combine several encoding in a single file.

If you need to do that more often I recommend to implement your own type, that has a Close method doing the right combination of Close and Flush calls.

Jesse McNelis

unread,
Dec 1, 2015, 6:51:19 PM12/1/15
to nicolas riesch, golang-nuts
transform.Writer doesn't know that the io.Writer you gave it has a
Flush() method and the bufio.Writer doesn't know that the io.Writer
you gave it is a file and needs to be Closed.
By keeping the abstraction to just an io.Writer the code can be more general.
Reply all
Reply to author
Forward
0 new messages