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

Patricia Arquette
Release: 2024-10-25 07:42:02
Original
779 people have browsed it

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:

<code class="go">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))</code>
Copy after login

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:

<code class="go">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))</code>
Copy after login

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.

The above is the detailed content of How do io.TeeReader and io.Copy differ in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!