Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

📚 Convert byte slice to io.Reader in Go

introduction slice

Please consider supporting us by disabling your ad blocker

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))
}

🧑‍🤝‍🧑 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