In-memory IO
The bytes
package offers common primitives to achieve streaming IO on blocks of bytes, stored in memory, represented by the bytes.Buffer
type. Since the bytes.Buffer
type implements both io.Reader
and io.Writer
interfaces it is a great option to stream data into or out of memory using streaming IO primitives.
The following snippet stores several string values in the byte.Buffer
variable, book
. Then the buffer is streamed to os.Stdout
:
func main() { var books bytes.Buffer books.WriteString("The Great Gatsby") books.WriteString("1984") books.WriteString("A Tale of Two Cities") books.WriteString("Les Miserables") books.WriteString("The Call of the Wild") books.WriteTo(os.Stdout) }
golang.fyi/ch10/bytesbuf0.go
The same example can easily ...
Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.