io.LimitReader() 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 LimitReader() function in Go language is used to return a “Reader” that reads from the stated “r” but it pauses if the EOF i.e, end of file is reached after reading the stated “n” number of bytes. 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 LimitReader(r Reader, n int64) Reader
Here, “r” is the stated Reader, and “n” is the number of bytes.
Return value: It returns a Reader that reads from the stated “r”.
Below examples illustrates the use of above method:
Example 1:
package main
import (
"fmt"
"io"
"os"
"strings"
)
func main() {
r := strings.NewReader( "Geeks\n" )
res := io.LimitReader(r, 3)
op, err := io.Copy(os.Stdout, res)
if err != nil {
panic(err)
}
fmt.Printf( "\nn: %v\n" , op)
}
|
Output:
Gee
n: 3
In the above example, the Copy() method is used in order to return the “Reader” and 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() {
r := strings.NewReader( "GfG\nis\na\nCS-Portal.\n" )
res := io.LimitReader(r, 8)
op, err := io.Copy(os.Stdout, res)
if err != nil {
panic(err)
}
fmt.Printf( "\nn: %v\n" , op)
}
|
Output:
GfG
is
a
n: 8
Last Updated :
03 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...