英文:
Go: Skip bytes from a stream using io.reader
问题
在Go语言中,使用io.Reader
跳过一定数量的字节的最佳方法是什么?也就是说,标准库中是否有一个函数,它接受一个_reader_和一个_count_,并从_reader_中读取和丢弃_count_个字节?
示例用法:
func DoWithReader(r io.Reader) {
SkipNBytes(r, 30); // 从reader中读取并丢弃30个字节
}
我不需要在流中向后移动,所以最好不要将io.Reader
转换为其他类型的读取器。
英文:
What is the best way in Go to skip forward a number of bytes in a stream using io.Reader
? That is, is there a function in the standard library which takes a reader and a count that will read and dispose count bytes from the reader?
Example use case:
func DoWithReader(r io.Reader) {
SkipNBytes(r, 30); // Read and dispose 30 bytes from reader
}
I don't need to go backwards in the stream so anything that can work without converting io.Reader
to another reader type would be preferred.
答案1
得分: 29
你可以使用以下代码片段:
import "io"
io.CopyN(io.Discard, yourReader, count)
它将请求的字节数复制到一个将读取内容丢弃的io.Writer
中。
如果你的io.Reader
是一个io.Seeker
,你可能想要考虑在流中进行定位,以跳过你想要跳过的字节数:
import "io"
switch r := yourReader.(type) {
case io.Seeker:
r.Seek(count, io.SeekCurrent)
default:
io.CopyN(io.Discard, r, count)
}
英文:
You could use this construction:
import "io"
io.CopyN(io.Discard, yourReader, count)
It copies the requested amount of bytes into an io.Writer
that discards what it reads.
If your io.Reader
is an io.Seeker
, you might want to consider seeking in the stream to skip the amount of bytes you want to skip:
import "io"
switch r := yourReader.(type) {
case io.Seeker:
r.Seek(count, io.SeekCurrent)
default:
io.CopyN(io.Discard, r, count)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论