Writing to string buffer or file, including stdout

115 views
Skip to first unread message

Tong Sun

unread,
Oct 31, 2015, 9:21:32 PM10/31/15
to golang-nuts
Hi, 

I need to write a program that writes either to a string buffer or to a file, of which if file name is passed as "-", will write to stdout instead. 

What's the suggested way of doing this? 

Thanks


Matt Harden

unread,
Oct 31, 2015, 10:45:07 PM10/31/15
to Tong Sun, golang-nuts
This is what the io.Writer interface is for. Create the writer as a *bytes.Buffer using new(bytes.Buffer), an *os.File using os.Create(filename), or use os.Stdout. All of these implement io.Writer, which means they can all be written to by the standard Go libraries.

Note that for performance you should probably wrap *os.File or os.Stdout in a bufio.Writer, and run Flush on this writer when you're done.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages