io.CopyBuffer() 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 CopyBuffer() function in Go language is the same as Copy() method but the only exception is that it exhibits through the supplied buffer if one is needed instead of allotting a provisional one. Where in case src is implemented by WriterTo or dst is implemented by ReaderFrom then no buffer will be used to perform the copy operation. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
func CopyBuffer(dst Writer, src Reader, buf byte) (written int64, err error)
Here, “dst” is the destination, “src” is the source from where the content is copied to the destination, and “buf” is the buffer that allows permanent space in memory.
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. However, if the buffer is nil then one is allotted else if the length of the buffer is zero then CopyBuffer panics.
Below examples illustrates the use of the above method:
GfG The number of bytes are: 4
GfG GeeksforGeeks is a CS-Portal The number of bytes are: 4 The number of bytes are: 29
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. Moreover, the same buffer is reused above while calling CopyBuffer() method, and no extra buffer is required to allocate.