Tuesday, April 16, 2024
HomeGolangConvert byte slice to io.Reader in Go (Golang)

Convert byte slice to io.Reader in Go (Golang)



To transform a byte slice to io.Reader in Go, create a brand new bytes.Reader object utilizing bytes.NewReader() operate with the byte slice argument. The bytes.Reader sort implements the io.Reader interface and can be utilized in any operate that requires it as an argument.

bundle fundamental

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

func fundamental() {
    knowledge := []byte("check byte slice")

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

    // learn the information from reader
    buf := make([]byte, len(knowledge))
    if _, err := reader.Learn(buf); err != nil {
        log.Deadly(err)
    }

    fmt.Println(string(buf))
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments