在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的ReadAtLeast()函數用於從指定的讀取器“r”讀取至指定的緩衝區“buf”,直到至少讀取了指定字節的最小數量。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。
用法:
func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)
在這裏,“r”是指定的讀取器,“buf”是指定的緩衝區,而“min”是讀取器讀取到給定緩衝區之前的最小字節數。
返回值:它返回指定緩衝區複製的字節數,並且如果讀取的字節數小於最小字節數,則還返回錯誤。在這裏,當且僅當錯誤為nil時,返回的“n”才會大於“min”字節。但是,僅當不讀取任何字節時,返回的錯誤是“EOF”。
注意:如果在讀取少於規定的“min”字節的字節後發生EOF,則此方法返回ErrUnexpectedEOF錯誤。但是,如果規定的最小字節數大於規定的緩衝區的長度,則此方法將返回ErrShortBuffer錯誤。但是,如果指定的讀取器在讀取了至少指定的最小字節後返回錯誤,則該錯誤將被拒絕。
範例1:
// Golang program to illustrate the usage of
// io.ReadAtLeast() 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")
// Defining buffer of specified length
// using make keyword
buffer:= make([]byte, 6)
// Calling ReadAtLeast method with its parameters
n, err:= io.ReadAtLeast(reader, buffer, 3)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("Number of bytes in the buffer:%d\n", n)
fmt.Printf("Content in buffer:%s\n", buffer)
}
輸出:
Number of bytes in the buffer:5 Content in buffer:Geeks
此處,由於錯誤為零,因此返回的‘n’(即5)大於‘min’(即3)。
範例2:
// Golang program to illustrate the usage of
// io.ReadAtLeast() 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("GeeksforGeeks")
// Defining buffer of specified length
// using make keyword
buffer:= make([]byte, 4)
// Calling ReadAtLeast method with its parameters
n, err:= io.ReadAtLeast(reader, buffer, 5)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("Number of bytes in the buffer:%d\n", n)
fmt.Printf("Content in buffer:%s\n", buffer)
}
輸出:
panic:short buffer goroutine 1 [running]: main.main() /tmp/sandbox041442440/prog.go:29 +0x20f
這裏,上述代碼中聲明的緩衝區的長度小於聲明的“min”字節,因此引發了錯誤。
相關用法
- 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.ReadAtLeast() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。