Skip to content
Related Articles

Related Articles

Improve Article

io.LimitReader() Function in Golang with Examples

  • Last Updated : 03 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 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:




// Golang program to illustrate the usage of
// io.LimitReader() function
  
// Including main package
package main
  
// Importing fmt, io, strings, and os
import (
    "fmt"
    "io"
    "os"
    "strings"
)
  
// Calling main
func main() {
  
    // Defining r using NewReader
    r := strings.NewReader("Geeks\n")
  
    // Calling LimitReader method with its parameters
    res := io.LimitReader(r, 3)
  
    // Calling Copy method with its parameters
    op, err := io.Copy(os.Stdout, res)
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    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:




// Golang program to illustrate the usage of
// io.LimitReader() function
  
// Including main package
package main
  
// Importing fmt, io, strings, and os
import (
    "fmt"
    "io"
    "os"
    "strings"
)
  
// Calling main
func main() {
  
    // Defining r using NewReader
    r := strings.NewReader("GfG\nis\na\nCS-Portal.\n")
  
    // Calling LimitReader method with its parameters
    res := io.LimitReader(r, 8)
  
    // Calling Copy method with its parameters
    op, err := io.Copy(os.Stdout, res)
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    fmt.Printf("\nn: %v\n", op)
}

Output:

GfG
is
a
n: 8



My Personal Notes arrow_drop_up
Recommended Articles
Page :