Bytes and Slices

This lesson provides necessary information about the bytes package provided by Golang.

The bytes package

Slices of bytes are so common that Go has a bytes package with manipulation functions for that kind of type. It is very analogous to the strings package. Moreover, it contains a very handy type Buffer:

import "bytes"
type Buffer struct {
  ...
}

It is a variable-sized buffer of bytes with Read and Write methods because reading and writing an unknown number of bytes is best done buffered.

A Buffer can be created as a value, like:

var buffer bytes.Buffer

or as a pointer with new as:

var r *bytes.Buffer = new(bytes.Buffer)

or created with the function:

func NewBuffer(buf []byte) *Buffer

This creates and initializes a new Buffer using buf as its initial contents. It is best to use NewBuffer only to read from buf. Here, is a simple example of code writing to a buffer:

Get hands-on with 1400+ tech skills courses.