reading from bytes.Buffer more than once

1,829 views
Skip to first unread message

Brian Slesinsky

unread,
Sep 1, 2013, 2:39:53 AM9/1/13
to golan...@googlegroups.com
I can write to a bytes.Buffer and then read from it, and that works fine. But I'd like to read the same buffer more than once, and all the methods for reading the buffer seem to be designed to prevent you from seeing the same bytes more than once. Why is that? It seems like it would be nice to have a Rewind() method to start reading the same bytes from the beginning, rather than having to awkwardly save another copy somewhere.

- Brian

Kyle Lemons

unread,
Sep 1, 2013, 3:26:14 AM9/1/13
to Brian Slesinsky, golang-nuts
Once you've written the data to your Buffer, use its data to make a Reader, which is seekable.


On Sat, Aug 31, 2013 at 11:39 PM, Brian Slesinsky <bsles...@gmail.com> wrote:
I can write to a bytes.Buffer and then read from it, and that works fine. But I'd like to read the same buffer more than once, and all the methods for reading the buffer seem to be designed to prevent you from seeing the same bytes more than once. Why is that? It seems like it would be nice to have a Rewind() method to start reading the same bytes from the beginning, rather than having to awkwardly save another copy somewhere.

- Brian

--
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/groups/opt_out.

Brian Slesinsky

unread,
Sep 1, 2013, 7:01:14 PM9/1/13
to golan...@googlegroups.com, Brian Slesinsky
Thanks, that works fine. (Actually, I copy to a []byte and create a new Reader for each read.)

Though it doesn't matter for my app, I wonder whether more performance sensitive code might want to avoid the unnecessary data copy.

- Brian

Brad Fitzpatrick

unread,
Sep 1, 2013, 7:11:05 PM9/1/13
to Brian Slesinsky, golang-nuts
The bytes.Buffer already has it in memory in a []byte, and its Bytes() method gives you that.

This is the most efficient:

 var buf bytes.Buffer
 buf.WriteString("Hello world")
 seekReader := bytes.NewReader(buf.Bytes())

Reply all
Reply to author
Forward
0 new messages