io.PipeWriter.Close() Function in Golang with Examples
Last Updated :
05 May, 2020
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 PipeWriter.Close() function in Go language is used to close the writer. However, successive reads from the PipeReader i.e, read half of the pipe will not return any bytes and an EOF error is returned. 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 (w *PipeWriter) Close() error
Here, “w” is a pointer to the PipeWriter. Where PipeWriter is the write half of a pipe.
Return value: It returns the content written before Close method. And successive reads from the PipeReader i.e read half of the pipe will not return any bytes after calling Close() method and an EOF error will be returned.
Example 1:
package main
import (
"fmt"
"io"
)
func main() {
pipeReader, pipeWriter := io.Pipe()
go func() {
pipeWriter.Write([]byte( "GfG" ))
pipeWriter.Write([]byte( "GeeksforGeeks" ))
pipeWriter.Close()
pipeWriter.Write([]byte( "GfG is a CS-Portal." ))
}()
buffer := make([]byte, 50)
for i := 0; i < 4; i++ {
n, err := pipeReader.Read(buffer)
if err != nil {
panic(err)
}
fmt.Printf( "%s\n" , buffer[:n])
}
}
|
Output:
GfG
GeeksforGeeks
panic: EOF
goroutine 1 [running]:
main.main()
/tmp/sandbox342418232/prog.go:42 +0x2d1
Here, the content of the two Write operations are returned as they are written before the Close() method but the content written after the Close method is not returned and an EOF error is thrown instead.
Example 2:
package main
import (
"fmt"
"io"
)
func main() {
pipeReader, pipeWriter := io.Pipe()
go func() {
pipeWriter.Close()
pipeWriter.Write([]byte( "GfG is a CS-Portal." ))
}()
buffer := make([]byte, 50)
for i := 0; i < 4; i++ {
n, err := pipeReader.Read(buffer)
if err != nil {
panic(err)
}
fmt.Printf( "%s\n" , buffer[:n])
}
}
|
Output:
panic: EOF
goroutine 1 [running]:
main.main()
/tmp/sandbox173042396/prog.go:40 +0x2d1
Here, no Write operation is performed before Close method so no content is returned and an EOF error is thrown.
Share your thoughts in the comments
Please Login to comment...