Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte slice to io.Reader

Tags:

go

People also ask

How to convert byte to io Reader?

To convert a byte slice to io. Reader in Go, create a new bytes. Reader object using bytes. NewReader() function with the byte slice argument.

What is io reader Golang?

The io.Reader interface is used by many packages in the Go standard library and it represents the ability to read a stream of data. More specifically allows you to read data from something that implements the io.Reader interface into a slice of bytes.

How do I create a byte array in Golang?

To create a byte in Go, assign an ASCII character to a variable. A byte in Golang is an unsigned 8-bit integer. The byte type represents ASCII characters, while the rune data type represents a broader set of Unicode characters encoded in UTF-8 format.

What is slice of byte in Golang?

Byte slices are a list of bytes that represent UTF-8 encodings of Unicode code points . Taking the information from above, we could create a byte slice that represents the word “Go”: bs := []byte{71, 111} fmt.Printf("%s", bs) // Output: Go. You may notice the %s used here. This converts the byte slice to a string.


To get a type that implements io.Reader from a []byte slice, you can use bytes.NewReader in the bytes package:

r := bytes.NewReader(byteData)

This will return a value of type bytes.Reader which implements the io.Reader (and io.ReadSeeker) interface.

Don't worry about them not being the same "type". io.Reader is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.