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 Pipe() function in Go language is used to create a concurrent in-memory pipe and can be applied in order to link the code that expects an io.Reader with the code that expects an io.Writer. Here, the Reads and Writes on the pipe are paired one-to-one except when more than one “Reads” are required to take a single “Write”. This indicates that each Write to the PipeWriter stops until it has satiated one or more than one Reads from the PipeReader that completely takes the written data.
However, the data is traced right away from the Write to the related Read(s) and there is no buffering internally. 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 Pipe() (*PipeReader, *PipeWriter)
Here, “PipeReader” is a pointer to the PipeReader. Where PipeReader is the read half of a pipe and “PipeWriter” is a pointer to the PipeWriter. Where PipeWriter is the write half of a pipe.
Return value: It returns a pointer to the PipeReader and PipeWriter.
Note: It is secured to call Read and Write simultaneously or with a Close. However, parallel calls to Read, and parallel calls to Write are also secured. The separate calls will be closed sequentially.
Example 1:
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
pipeReader, pipeWriter := io.Pipe()
go func() {
fmt.Fprint(pipeWriter, "Geeks\n" )
pipeWriter.Close()
}()
buffer := new (bytes.Buffer)
buffer.ReadFrom(pipeReader)
fmt.Print(buffer.String())
}
|
Output:
Geeks
Example 2:
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
pipeReader, pipeWriter := io.Pipe()
go func() {
fmt.Fprint(pipeWriter, "GeeksforGeeks\nis\na\nCS-Portal.\n" )
pipeWriter.Close()
}()
buffer := new (bytes.Buffer)
buffer.ReadFrom(pipeReader)
fmt.Print(buffer.String())
}
|
Output:
GeeksforGeeks
is
a
CS-Portal.