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 be updated to stream the content to a regular file as shown in the following abbreviate code snippet:

func main() { 
   var books bytes.Buffer 
   books.WriteString("The Great Gatsby
") 
   books.WriteString("1984
") 
   books.WriteString("A Take of Two Cities
") 
   books.WriteString("Les Miserables
") 
   books.WriteString("The Call of the Wild
") 
 
   file, err := os.Create("./books.txt") 
   if err != nil { 
         fmt.Println("Unable to create file:", err) 
         return 
   } 
   defer file.Close() 
   books.WriteTo(file) 
} 

golang.fyi/ch10/bytesbuf1.go

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.62.122