Ask Your Question
3

What is the correct method for transferring data from an io.Reader to a destination bytes.Buffer in Golang without any intermediate steps?

asked 2023-03-17 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-04-13 01:00:00 +0000

ladyg gravatar image

The correct method for transferring data from an io.Reader to a destination bytes.Buffer in Golang without any intermediate steps is to use the Copy() function from the io package.

Here is an example code snippet:

package main

import (
    "bytes"
    "io"
    "os"
)

func main() {
    // Open a file to read
    file, err := os.Open("example.txt")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // Create a bytes.Buffer to write to
    buffer := bytes.Buffer{}

    // Copy the contents of the file to the buffer
    _, err = io.Copy(&buffer, file)
    if err != nil {
        panic(err)
    }

    // Print the contents of the buffer
    println(buffer.String())
}

In this code, we open a file to read, then create a bytes.Buffer to write to. We use the io.Copy() function to transfer the contents of the file to the buffer. Finally, we print the contents of the buffer to verify that the data was transferred correctly.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-17 11:00:00 +0000

Seen: 13 times

Last updated: Apr 13 '21