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


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

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的LimitReader()函數用於返回從指定的“r”讀取的“Reader”,但如果在讀取指定的“n”字節數後到達EOF(即文件末尾),它將暫停。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。

用法:

func LimitReader(r Reader, n int64) Reader

此處,“r”是指定的讀取器,而“n”是字節數。

返回值:它返回從指定的“r”讀取的Reader。

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



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

輸出:

Gee
n:3

在上麵的示例中,使用Copy()方法返回“Reader”,並使用NewReader()方法從寫入內容的位置寫入字符串。

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

輸出:

GfG
is
a
n:8



相關用法


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