io.PipeWriter.CloseWithError() 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 PipeWriter.CloseWithError() 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 the error err or EOF error is returned if the error is nil. 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) CloseWithError(err error) error
Here, “w” is a pointer to the PipeWriter. Where PipeWriter is the write half of a pipe and “err” is the error as stated by us in the code which is printed if an error occurs.
Return value: It returns an error if any as stated by us else it returns an EOF if the error is nil.
Note: This method never rewrites the former error if it resides and every time returns “nil”.
Example 1:
package main
import (
"fmt"
"io"
)
func main() {
pipeReader, pipeWriter := io.Pipe()
data := make([]byte, 20)
go func() {
pipeReader.Read(data)
pipeReader.CloseWithError(fmt.Errorf( "There is an " +
"error in the code written!" ))
}()
for i := 0; i < 1; i++ {
n, err := pipeWriter.Write([]byte( "GeeksforGeeks!" ))
if err != nil {
panic(err)
}
fmt.Printf( "%v\n" , string(data))
fmt.Printf( "%v\n" , n)
}
}
|
Output:
GeeksforGeeks!
14
Here, no error is returned as CloseWithError() method was not called here because the loop stops after one read operation only.
Example 2:
package main
import (
"fmt"
"io"
)
func main() {
pipeReader, pipeWriter := io.Pipe()
data := make([]byte, 20)
go func() {
pipeReader.Read(data)
pipeReader.CloseWithError(fmt.Errorf( "There is" +
" an error in the code written!" ))
}()
for i := 0; i < 2; i++ {
n, err := pipeWriter.Write([]byte( "GeeksforGeeks!" ))
if err != nil {
panic(err)
}
fmt.Printf( "%v\n" , string(data))
fmt.Printf( "%v\n" , n)
}
}
|
Output:
GeeksforGeeks!
14
panic: There is an error in the code written!
goroutine 1 [running]:
main.main()
/tmp/sandbox246824679/prog.go:39 +0x3c2
Here, an error is thrown as CloseWithError() method is called because “for” loop stops after the second iteration. And the error returned here is as stated by us.
Last Updated :
10 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...