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.
Syntax:
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:
Example 1:
package main
import (
"fmt"
"io"
"os"
"strings"
)
func main() {
src := strings.NewReader( "GfG\n" )
dst := os.Stdout
buffer := make([]byte, 1)
bytes, err := io.CopyBuffer(dst, src, buffer)
if err != nil {
panic(err)
}
fmt.Printf( "The number of bytes are: %d\n" , bytes)
}
|
Output:
GfG
The number of bytes are: 4
Example 2:
package main
import (
"fmt"
"io"
"os"
"strings"
)
func main() {
src1 := strings.NewReader( "GfG\n" )
src2 := strings.NewReader( "GeeksforGeeks is a CS-Portal\n" )
dst := os.Stdout
buffer := make([]byte, 1)
bytes1, err := io.CopyBuffer(dst, src1, buffer)
bytes2, err := io.CopyBuffer(dst, src2, buffer)
if err != nil {
panic(err)
}
fmt.Printf( "The number of bytes are: %d\n" , bytes1)
fmt.Printf( "The number of bytes are: %d\n" , bytes2)
}
|
Output:
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 May, 2020
Like Article
Save Article