在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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。