Search code examples
pointersmethodsgoembedding

bytes.Reader, replacing underlying []byte array


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.


Solution

  • 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.