當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang io.SectionReader.Seek()用法及代碼示例

在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 wherece的三個常量值如下:



  • 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”,這意味著它相對於末尾進行搜索。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.SectionReader.Seek() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。