英文:
Wrap io.PipeReader to store progress
问题
我想要在io.Pipe中跟踪进度。我设计了以下的结构体ProgressPipeReader,它包装了io.PipeReader,并将进度以字节的形式存储在ProgressPipeReader.progress中:
type ProgressPipeReader struct {
    io.PipeReader
    progress int64
}
func (pr *ProgressPipeReader) Read(data []byte) (int, error) {
    n, err := pr.PipeReader.Read(data)
    if err == nil {
        pr.progress += int64(n)
    }
    return n, err
}
不幸的是,我似乎无法使用它来包装io.PipeReader。以下代码片段:
pr, pw := io.Pipe()
pr = &ProgressPipeReader{PipeReader: pr}
会产生错误:
cannot use pr (type *io.PipeReader) as type io.PipeReader in field value
有什么提示吗?
英文:
I would like to keep track of the progress in an io.Pipe. I came up with the following struct ProgressPipeReader which wraps io.PipeReader, storing the progress in bytes inside ProgressPipeReader.progress:
type ProgressPipeReader struct {
        io.PipeReader
        progress int64
}
func (pr *ProgressPipeReader) Read(data []byte) (int, error) {
        n, err := pr.PipeReader.Read(data)
        if err == nil {
                pr.progress += int64(n)
        }
        return n, err
}
Unfortunately, I can't seem to use it to wrap an io.PipeReader. The following snippet
pr, pw := io.Pipe()
pr = &ProgressPipeReader{PipeReader: pr}
yields the error
cannot use pr (type *io.PipeReader) as type io.PipeReader in field value
Any hints?
答案1
得分: 2
根据错误描述,你试图将*io.PipeReader的值存储在io.PipeReader字段中。你可以通过更新结构体定义为正确的类型来解决这个问题:
type ProgressPipeReader struct {
    *io.PipeReader
    progress int64
}
英文:
As the error describes, you are trying to store a *io.PipeReader value in a io.PipeReader field. You can fix this by updating your struct definition to the correct type:
type ProgressPipeReader struct {
        *io.PipeReader
        progress int64
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论