io.Copy() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The Copy() function in Go language is used to copy from the stated src i.e, source to the dst i.e, destination till either the EOF i.e, end of file is attained on src or an error is thrown. Here, when src is implemented by WriterTo interface then the copy is implemented by a call to src.WriteTo(dst). else, if dst is implemented by the ReaderFrom interface then the copy is implemented by a call to dst.ReadFrom(src). Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
func Copy(dst Writer, src Reader) (written int64, err error)
Here, “dst” is the destination and “src” is the source from where the content is copied to the destination.
Return value: It returns the total number of bytes of type int64 that are copied to the “dst” and also returns the first error that is faced while copying from src to dst, if any. And if there is no error in copying then “nil” is returned.
Below examples illustrates the use of above method:
GeeksforGeeks The number of bytes are: 14
Nidhi: F Rahul: M Nisha: F The number of bytes are: 27
Here, in the above example NewReader() method of strings is used from where the content to be copied is read. And “Stdout” is used here in order to create a default file descriptor where the copied content is written.