"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do io.TeeReader and io.Copy differ in Go?

How do io.TeeReader and io.Copy differ in Go?

Published on 2024-11-04
Browse:129

How do io.TeeReader and io.Copy differ in Go?

Differences between io.TeeReader and io.Copy

In Go, io.TeeReader and io.Copy facilitate data transfer from a io.Reader to a io.Writer. While both functions serve this purpose, they offer distinct functionality.

io.Copy

io.Copy is a simple and straightforward function that efficiently copies data from a source reader to a destination writer. It focuses solely on data transfer and returns no values.

io.TeeReader

io.TeeReader provides a more versatile approach. Unlike io.Copy, io.TeeReader creates a new io.Reader that wraps the original reader. When reading from this new reader, data is simultaneously written to the provided io.Writer. This feature is useful when you need to both inspect and process copied data.

Example Usage

To illustrate the difference, consider a scenario where we need to copy data from a reader to standard output while also computing the MD5 hash of the copied content.

Using io.TeeReader:

r := io.TeeReader(strings.NewReader(s), os.Stdout)
h := md5.New()
if _, err := io.Copy(h, r); err != nil { panic(err) }
fmt.Printf("Hash: %x\n", h.Sum(nil))

In this example, io.TeeReader allows us to simultaneously print the copied data to standard output and compute the MD5 hash using the h.Sum(nil) function.

io.MultiWriter

It's worth noting that io.TeeReader's functionality can also be achieved using io.MultiWriter:

mw := io.MultiWriter(h, os.Stdout)
if _, err := io.Copy(mw, strings.NewReader(s)); err != nil { panic(err) }
fmt.Printf("Hash: %x\n", h.Sum(nil))

io.MultiWriter combines multiple writers into a single destination, effectively allowing data to be written to multiple locations simultaneously. In this case, h receives the copied data for hash computation, while os.Stdout displays it.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3