bytes.Reader,替换底层的[]byte数组。

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

bytes.Reader, replacing underlying []byte array

问题

我一直在尝试找到一种好的方法来传递一个Reader接口{},而不必重新创建与io.Reader相关联的方法。

这是我正在使用的代码:

type EZReader struct {
    data *bytes.Reader
}

func (self *EZReader) Replace(input []byte) {
    self.data = bytes.NewReader(input)
}

func (self *EZReader) Read(p []byte) (n int, err error) {
    return self.data.Read(p)
}

感觉不太对,有没有更好的方法呢?

我的想法是,我可以将这个io.Reader传递给一个函数,并在需要时更换底层数组,而不必重新分配要使用它的对象,例如json解码器。

英文:

I've been trying to find a nice way to hand off a Reader interface{} without recreating the methods associated with a io.Reader.

This is what I'm using:

type EZReader struct {
    data *bytes.Reader
}

func (self *EZReader) Replace(input []byte) {
    self.data = bytes.NewReader(input)
}

func (self *EZReader) Read(p []byte) (n int, err error) {
    return self.data.Read(p)
}

It feels, not right, is there a better way to do this?

The idea is I can then hand off this io.Reader to a function and change out the underlying array as

I need it without having to reallocating the object that wants to use it, in this case the json decoder.

答案1

得分: 1

如果在结构体中嵌入一个字段,那么该字段的所有方法也可以在结构体上调用。因此,如果你这样写:

type EZReader struct {
    *bytes.Reader
}

你就不需要重新实现Read()方法。这样的字段的行为就像它被命名为Reader一样。请注意,你无法通过这种方式避免暴露该字段。

英文:

If you embed a field in a struct, all the methods of that field can be called on the struct, too. So if you write

type EZReader struct {
    *bytes.Reader
}

you don't have to reimplement Read(). Such a field behaves as if it was named Reader. Notice that you can't avoid exposing the field this way.

huangapple
  • 本文由 发表于 2014年12月24日 05:52:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/27628548.html
匿名

发表评论

匿名网友

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

确定