What is the io.Copy() Function in Golang

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.


func Copy(dst Writer, src Reader) (written int64, err error)


  1. dst: The destination io.Writer where the data will be written.
  2. src: The source io.Reader from which the data will be read.
  3. written: The number of bytes copied from the source to the destination.
  4. err: An error if one occurred during the copy process; otherwise, it will be nil.


package main

import (

func main() {
  err := CopyFile("data.txt", "my_text_file.txt")
  if err != nil {
    fmt.Println("Error copying file:", err)
  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


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.

Leave a Comment