将io.PipeReader包装起来以存储进度。

huangapple go评论90阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2017年6月26日 19:56:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/44759185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定