Cookies management by TermsFeed Cookie Consent

📚 Convert byte slice to io.Reader in Go

introduction slice

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. The bytes.Reader type implements the io.Reader interface and can be used in any function that requires it as an argument.

package main

import (
    "bytes"
    "fmt"
    "log"
)

func main() {
    data := []byte("test byte slice")

    // byte slice to bytes.Reader, which implements the io.Reader interface
    reader := bytes.NewReader(data)

    // read the data from reader
    buf := make([]byte, len(data))
    if _, err := reader.Read(buf); err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(buf))
}

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🧑‍🤝‍🧑 Copy a slice in Go

Learn how to make a deep copy of a slice
introduction slice

🔎 Check if the slice contains the given value in Go

Learn how to write a function that checks if a slice has a specific value
introduction slice

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice