io.MultiReader() 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 MultiReader() function in Go language is used to return a “Reader” that is the logical concatenation of all the stated input readers. However, these stated readers are read in a sequence. And after all the stated input returns an EOF i.e, end of the file, “Read” will return an EOF. 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 MultiReader(readers ...Reader) Reader
Here, “readers” is the number of stated Readers.
Return value: It returns a “Reader” that is the logical concatenation of all the given input readers. And if any of the stated readers return a non-nil error or a non-EOF error then “Read” returns that error.
Below examples illustrates the use of the above method:
Example 1:
package main
import (
"fmt"
"io"
"os"
"strings"
)
func main() {
reader1 := strings.NewReader( "Geeks\n" )
reader2 := strings.NewReader( "GfG\n" )
reader3 := strings.NewReader( "CS\n" )
r := io.MultiReader(reader1, reader2, reader3)
Reader, err := io.Copy(os.Stdout, r)
if err != nil {
panic(err)
}
fmt.Printf( "n: %v\n" , Reader)
}
|
Output:
Geeks
GfG
CS
n: 13
In the above example, Copy() method is used in order to return the result of all the concatenated readers, and the NewReader() method of strings is used from where the content to be read is written.
Example 2:
package main
import (
"fmt"
"io"
"os"
"strings"
)
func main() {
reader1 := strings.NewReader( "104\n" )
reader2 := strings.NewReader( "33.3\n" )
reader3 := strings.NewReader( "703243242\n" )
r := io.MultiReader(reader1, reader2, reader3)
Reader, err := io.Copy(os.Stdout, r)
if err != nil {
panic(err)
}
fmt.Printf( "n: %v\n" , Reader)
}
|
Output:
104
33.3
703243242
n: 19
Last Updated :
03 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...