📜  Golang 中的 io.SectionReader.Seek()函数示例

📅  最后修改于: 2021-10-24 13:23:27             🧑  作者: Mango

在 Go 语言中, io包为 I/O 原语提供基本接口。它的主要工作是封装这种原语之王的持续实现。 Go 语言中的SectionReader.Seek()函数用于在声明的偏移量和从何而来的帮助下找到新的偏移量。而且,这个函数是在io包下定义的。在这里,您需要导入“io”包才能使用这些功能。

句法:

func (s *SectionReader) Seek(offset int64, whence int) (int64, error)

这里,“s”是指向由NewSectionReader方法返回的SectionReader的指针,“offset”是 int64 类型,“whence”是 int 类型。

返回值:它在给定的偏移量加上 wherece 的帮助下返回一个新的偏移量,如果有的话也返回一个错误。

注: Seek whence共有三个常数值,分别如下:

  • SeekStart = 0,它相对于指定文件的开头进行搜索。
  • SeekCurrent = 1,它相对于指定文件的最新偏移量进行搜索。
  • SeekEnd = 2,它相对于指定文件的结尾进行搜索。

示例 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)
}

输出:

The new offset is: 6

在上面的示例中,Seek whence 的值为 1,这意味着它是“SeekCurrent”,因此它相对于当前偏移量进行搜索。

示例 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)
}

输出:

The new offset is: 10

这里,Seek wherece 的值是“SeekEnd”,这意味着它相对于终点进行搜索。