Go equivalent of Python's io.BytesIO
io.BytesIO
in Python 3.x provides a convenient way of having a file-like object that actually streams to/from memory.
In Go, the equivalent problem is to have a io.Reader
and/or and io.Writer
(i.e. the equivalent of Python’s file-like object) that is backed by a []byte
or a string
.
Solution: Use bytes.Buffer
!
// Initialize an empty buffer (e.g. for writing)
buf := &bytes.Buffer{}
// Initialize a buffer with a []byte content (e.g. for reading)
myBytes := ...
buf := bytes.NewBuffer(myBytes)
// Initialize a buffer with string
myStr := "test 123"
buf := bytes.NewBufferString(myStr)