3 回答
TA贡献1844条经验 获得超8个赞
TLDR:
my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42))
完整答案:
@monicuta提到的io.ReadFull效果很好。在这里,我提供了另一种方法。它通过链接ioutil.ReadAll和io.LimitReader在一起工作。让我们先阅读文档:
$ go doc ioutil.ReadAll
func ReadAll(r io.Reader) ([]byte, error)
ReadAll reads from r until an error or EOF and returns the data it read. A
successful call returns err == nil, not err == EOF. Because ReadAll is
defined to read from src until EOF, it does not treat an EOF from Read as an
error to be reported.
$ go doc io.LimitReader
func LimitReader(r Reader, n int64) Reader
LimitReader returns a Reader that reads from r but stops with EOF after n
bytes. The underlying implementation is a *LimitedReader.
因此,如果您想从中获取42个字节myReader,则可以执行此操作
import (
"io"
"io/ioutil"
)
func main() {
// myReader := ...
my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42))
if err != nil {
panic(err)
}
//...
}
这是与 io.ReadFull
$ go doc io.ReadFull
func ReadFull(r Reader, buf []byte) (n int, err error)
ReadFull reads exactly len(buf) bytes from r into buf. It returns the number
of bytes copied and an error if fewer bytes were read. The error is EOF only
if no bytes were read. If an EOF happens after reading some but not all the
bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and
only if err == nil. If r returns an error having read at least len(buf)
bytes, the error is dropped.
import (
"io"
)
func main() {
// myReader := ...
buf := make([]byte, 42)
_, err := io.ReadFull(myReader, buf)
if err != nil {
panic(err)
}
//...
}
与相比io.ReadFull,优点是您无需手动创建buf,其中len(buf)要读取的字节数是多少,然后buf在读取时作为参数传递
相反,您只是简单地告诉io.LimitReader您要从中获取最多42个字节myReader,然后调用ioutil.ReadAll以读取所有字节,并将结果作为字节片返回。如果成功,则保证返回的切片长度为42。
- 3 回答
- 0 关注
- 446 浏览
添加回答
举报