Open In App

io.SectionReader.Seek() 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 SectionReader.Seek() function in Go language is used to find a new offset with the help of the stated offset and whence. 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 (s *SectionReader) Seek(offset int64, whence int) (int64, error)

Here, “s” is a pointer to the SectionReader which is returned by the NewSectionReader method, “offset” is of type int64, and “whence” is of type int.

Return value: It returns a new offset with the help of the given offset plus whence and also returns an error if any.



Note: There are three constant values of Seek whence, which are as follows:

Example 1:




// Golang program to illustrate the usage of
// io.SectionReader.Seek() function
  
// Including main package
package main
  
// Importing fmt, io, and strings
import (
    "fmt"
    "io"
    "strings"
)
  
// Calling main
func main() {
  
    // Defining reader using NewReader method
    reader := strings.NewReader("Geeks")
  
    // Calling NewSectionReader method with its parameters
    r := io.NewSectionReader(reader, 1, 4)
  
    // Calling Seek method with its parameters
    Newoffset, err := r.Seek(6, 1)
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    fmt.Printf("The new offset is: %v\n", Newoffset)
}

Output:

The new offset is: 6

In the above example, the value of Seek whence is 1 which means it is “SeekCurrent” so it seeks relative to the current offset.

Example 2:




// Golang program to illustrate the usage of
// io.SectionReader.Seek() function
  
// Including main package
package main
  
// Importing fmt, io, and strings
import (
    "fmt"
    "io"
    "strings"
)
  
// Calling main
func main() {
  
    // Defining reader using NewReader method
    reader := strings.NewReader("Geeks")
  
    // Calling NewSectionReader method with its parameters
    r := io.NewSectionReader(reader, 1, 4)
  
    // Calling Seek method with its parameters
    Newoffset, err := r.Seek(6, io.SeekEnd)
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    fmt.Printf("The new offset is: %v\n", Newoffset)
}

Output:

The new offset is: 10

Here, the value of Seek whence is “SeekEnd” which means it seeks relative to the end.


Article Tags :