在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的ReadFull()函數用於從指定的讀取器“r”讀入指定的緩衝區“buf”,並且複製的字節與指定緩衝區的長度完全相等。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。
用法:
func ReadFull(r Reader, buf []byte) (n int, err error)
在這裏,“r”是指定的讀取器,“buf”是指定長度的緩衝區。
返回值:它返回指定緩衝區複製的字節數,如果讀取的字節數小於指定緩衝區的長度,則返回錯誤。在這裏,當且僅當錯誤為nil時,返回的“n”才等於指定的緩衝區的長度。但是,僅當不讀取任何字節時,返回的錯誤是“EOF”。
注意:如果在讀取較少的字節而不是全部字節後發生EOF,則此方法將返回ErrUnexpectedEOF錯誤。但是,如果指定的讀取器在讀取至少緩衝區長度後返回錯誤,則該錯誤將被拒絕。
範例1:
// Golang program to illustrate the usage of
// io.ReadFull() 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, 4)
// Calling ReadFull method with its parameters
n, err:= io.ReadFull(reader, buffer)
// 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:4 Content in buffer:Geek
在這裏,由於錯誤為零,因此返回的‘n’(即4)等於‘buf’的長度。
範例2:
// Golang program to illustrate the usage of
// io.ReadFull() 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 ReadFull method with its parameters
n, err:= io.ReadFull(reader, buffer)
// 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:unexpected EOF goroutine 1 [running]: main.main() /tmp/sandbox503804944/prog.go:29 +0x210
在這裏,上述代碼中說明的緩衝區的長度大於從讀取器讀取的字節,因此會引發EOF錯誤。
相關用法
- 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.ReadFull() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。