Grow ensures that there are at least n bytes to write.The call to 
bb.Grow(2) in the example will not change the underlying byte slice, 
because there are already two bytes to write. A call to 
bb.Grow(initial+growth), which is bb.Grow(4) in the example, will enlarge 
the buffer to 8 bytes and will not result in a panic.

The number of bytes available for writing are given by bb.Cap() - bb.Len(). 
In the example bb.Len() stays 0 because nothing is written into the buffer. 
I would also keep in mind that bb.Grow() is an optimization if you are 
writing smaller data chunks into a buffer that gets larger than 64 bytes to 
prevent multiple allocations and copies. Anyway your program should work 
fine without calling Grow. 

Note also that bytes.Buffer works as an io.Reader and io.Writer. If you 
don't need those interfaces a pure byte slice and the builtin append 
function will be faster.

Here is the changed program that doesn't 
panic: https://play.golang.org/p/8nSATjpNjR

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to