io.MultiWriter() 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 MultiWriter() function in Go language is used to create a writer that copies its writes to each and every given writers, which is the same as the Unix command tee(1). Here, each and every write is written to each of the included writer, one by one. 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 MultiWriter(writers ...Writer) Writer
Here, “writers” is the number of writers stated as a parameter in this function.
Return value: It returns a Writer which includes the number of bytes present in the stated buffer and also returns an error if any. And if a stated writer returns an error then the entire write operation ceases and doesn’t extend down the list.
Example 1:
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
func main() {
reader := strings.NewReader( "Geeks" )
var buffer1, buffer2 bytes.Buffer
writer := io.MultiWriter(&buffer1, &buffer2)
n, err := io.Copy(writer, reader)
if err != nil {
panic(err)
}
fmt.Printf( "Number of bytes in the buffer: %v\n" , n)
fmt.Printf( "Buffer1: %v\n" , buffer1.String())
fmt.Printf( "Buffer2: %v\n" , buffer2.String())
}
|
Output:
Number of bytes in the buffer: 5
Buffer1: Geeks
Buffer2: Geeks
Here, Copy() method is used to return the number of bytes contained in the buffer. And here the content of both the buffer is the same as the stated writer duplicates its write to all the other writers.
Example 2:
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
func main() {
reader := strings.NewReader( "GeeksforGeeks\nis\na\nCS-Portal!" )
var buffer1, buffer2 bytes.Buffer
writer := io.MultiWriter(&buffer1, &buffer2)
n, err := io.Copy(writer, reader)
if err != nil {
panic(err)
}
fmt.Printf( "Number of bytes in the buffer: %v\n" , n)
fmt.Printf( "Buffer1: %v\n" , buffer1.String())
fmt.Printf( "Buffer2: %v\n" , buffer2.String())
}
|
Output:
Number of bytes in the buffer: 29
Buffer1: GeeksforGeeks
is
a
CS-Portal!
Buffer2: GeeksforGeeks
is
a
CS-Portal!
Last Updated :
05 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...