Example: io.Copy
Quick Example
io.Copy acts like a direct, high-efficiency data pipeline. It streams data from a source (io.Reader) to a destination (io.Writer) without loading the entire content into memory. This makes it the perfect tool for handling large files or network streams.
Output:
io.Copy is a zero-waste mover. Under the hood, it uses a default 32 KB temporary buffer to forward data streams, keeping memory consumption extremely low.
If you need to fine-tune the buffer size for specific use cases, use io.CopyBuffer(dst Writer, src Reader, buf []byte):
- dst / src: The destination writer and source reader.
- buf: A pre-allocated byte slice that you provide. If you pass
nil, the system defaults to a 32 KB buffer, behaving exactly likeio.Copy.
Copying Large Files with io.Copy
When dealing with large files (like videos, zip archives, or massive logs) that span hundreds of megabytes or gigabytes, loading them completely into memory using os.ReadFile or io.ReadAll will likely trigger an OOM (Out of Memory) crash.
Whether you are copying a 10 MB file or a 10 GB file, io.Copy keeps your memory footprint consistently low.