18

What is the easiest method to create an empty buffer of sizen in Go usingbytes.NewBuffer()?

askedJan 19, 2018 at 6:20
cmcginty's user avatar
1
  • 6
    NewBuffer(make([]byte,0,N))?CommentedJan 19, 2018 at 6:25

2 Answers2

29

Adding some additional info here. The quick way to create a new buffer is briefly mentioned at the end of the doc string:

b := new(bytes.Buffer)

or

b := &bytes.Buffer{}

TheBuffer struct define includes a 64 byte internalbootstrap field that is initially used for small allocations. Once the default size is exceeded, a byte sliceBuffer.buf is created and internally maintained.

As @leafbebop suggested we can pre-initalize thebuf field of theBuffer struct using a new slice.

b := bytes.NewBuffer(make([]byte,0,N))

I also found another option to use theGrow() method:

b := new(bytes.Buffer)b.Grow(n)

Also it's interesting to point out that the internalbuf slice will grow at a rate ofcap(buf)*2 + n. This means that if you've written 1MB into a buffer and then add 1 byte, yourcap() will increase to2097153 bytes.

answeredJan 19, 2018 at 9:18
cmcginty's user avatar
Sign up to request clarification or add additional context in comments.

Comments

0

Thebytes.buffer zero value is usable as is, so you can skip the initialization step. Code snippet fromdocs.

var b bytes.Buffer // A Buffer needs no initialization.b.Write([]byte("Hello "))
answeredMar 13, 2023 at 21:31
E.Howard's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.