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

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

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

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice

🏟️ Capacity and length of a slice in Go

Learn what is the difference between length and capacity of a slice
introduction slice array