Search code examples
go

Idiomatically buffer os.Stdout


os.Stdout.Write() is an unbuffered write. To get a buffered write, one can use the following:

f := bufio.NewWriter(os.Stdout)
f.Write(b)

Question:

Is there a more idiomatic way to get buffered output?


Solution

  • No, that is the most idiomatic way to buffer writes to Stdout. In many cases, you will want to also add a defer:

    f := bufio.NewWriter(os.Stdout)
    defer f.Flush()
    f.Write(b)
    

    This will ensure that the buffer is flushed when you return from the function.