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


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

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的NewSectionReader()函數用於返回從指定的讀取器“r”讀取的SectionReader,該讀取器從指定的偏移量“off”開始並以EOF終止,即在給定“n”字節數之後的文件結尾。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。

用法:

func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader

在這裏,“r”是從中讀取內容的讀取器,“off”是從內容讀取開始的指定偏移量,“n”是從其讀取內容的字節數。

返回值:它返回一個從指定的讀取器“r”讀取的“SectionReader”,該讀取器從指定的偏移量“off”開始,並以EOF終止,即在給定的“n”字節數之後的文件結尾。

以下示例說明了上述方法的使用:



範例1:

// Golang program to illustrate the usage of 
// io.NewSectionReader() function 
  
// Including main package 
package main 
  
// Importing fmt, io, strings, and os 
import ( 
    "fmt"
    "io"
    "os"
    "strings"
) 
  
// Calling main 
func main() { 
  
    // Defining reader using NewReader method 
    reader:= strings.NewReader("Geeks\n") 
  
    // Calling NewSectionReader method with its parameters 
    r:= io.NewSectionReader(reader, 3, 5) 
  
    // Calling Copy method with its parameters 
    Reader, err:= io.Copy(os.Stdout, r) 
  
    // If error is not nil then panics 
    if err != nil { 
        panic(err) 
    } 
  
    // Prints output 
    fmt.Printf("n:%v\n", Reader) 
}

輸出:

ks
n:3

在上麵的示例中,使用Copy()方法返回輸出,並使用NewReader()字符串方法(從此處寫入要讀取的內容)。

範例2:

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

輸出:

rGeeks
is
a
CS-Portal.
n:23

此處,內容從偏移量“7”開始,並在字節數達到“40”之後終止。但在此處返回的輸出中,複製的內容為“23”字節,因此“n”為23。




相關用法


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