Golang bytes.Buffer.NewBuffer() function example

package bytes

NewBuffer creates and initializes a new Buffer using the given input as its initial contents. It is intended to prepare a Buffer to read existing data. It can also be used to size the internal buffer for writing. To do that, the new Buffer size should be more than zero and better still is to specify a desired capacity/size.


In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

Golang bytes.NewBuffer() function usage example

 package main

 import (
 "bytes"
 "fmt"
 )

 func main() {
 newbuf := bytes.NewBuffer([]byte("abcdefg"))

 var buff [7]byte

 newbuf.Read(buff[:])

 fmt.Println(string(buff[:]))
 }

Output :

abcdefg

Reference :

http://golang.org/pkg/bytes/#NewBuffer

Advertisement