Golang io.Copy() is a built-in utility function that “copies data from a source (reader) to a destination (writer) until either an error occurs or the end of the source is reached (EOF)”. The function helps transfer data between different data streams without managing intermediate buffers yourself.
Syntax
func Copy(dst Writer, src Reader) (written int64, err error)
Parameters
- dst: The destination io.Writer where the data will be written.
- src: The source io.Reader from which the data will be read.
- written: The number of bytes copied from the source to the destination.
- err: An error if one occurred during the copy process; otherwise, it will be nil.
Example
package main
import (
"fmt"
"io"
"os"
)
func main() {
err := CopyFile("data.txt", "my_text_file.txt")
if err != nil {
fmt.Println("Error copying file:", err)
return
}
fmt.Println("File copied successfully")
}
func CopyFile(dstPath, srcPath string) error {
// Open the source file for reading
srcFile, err := os.Open(srcPath)
if err != nil {
return err
}
defer srcFile.Close()
// Create the destination file for writing
dstFile, err := os.Create(dstPath)
if err != nil {
return err
}
defer dstFile.Close()
// Copy the data from the source file to the destination file
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return err
}
return nil
}
Output
File copied successfully
In this code example, the CopyFile() function takes a source file path and a destination file path, opens the source file for reading, creates the destination file for writing, and then uses io.Copy() function to copy the data from the source to the destination.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.