在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
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.LimitReader() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。