📅  最后修改于: 2023-12-03 15:31:01.073000             🧑  作者: Mango
In Go, a reader is an interface that allows reading a sequence of bytes. It is used extensively in I/O operations, such as reading data from files, sockets, or HTTP responses. In this tutorial, we will learn how to create a reader from a byte array, and use it to read data in memory.
To create a reader from a byte array, we can use the bytes.NewReader()
function. This function takes a byte slice as a parameter, and returns a *bytes.Reader
value which implements the io.Reader
interface.
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
data := []byte("Hello, World!")
reader := bytes.NewReader(data)
buffer := make([]byte, 5)
for {
n, err := reader.Read(buffer)
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
fmt.Print(string(buffer[:n]))
}
}
In the example above, we have created a byte array containing the string "Hello, World!", and created a *bytes.Reader
from it using the bytes.NewReader()
function. We then created a buffer of length 5, and used a for
loop to read data from the reader in chunks of at most 5 bytes, until we reach the end of the reader.
In this tutorial, we have learned how to create a reader from a byte array, and use it to read data in memory. This technique can be useful in situations where we need to manipulate data before writing it to a file or sending it over a network, or when we need to read data from a non-standard source, such as a memory-mapped file or a buffer in shared memory.