Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new method to an existing (standard) type

Tags:

go

I'm writing some code that needs functionality that is almost satisfied by the ReadBytes method in the bufio package. Specifically, that method reads from a Reader until it encounters a particular byte. I need something that reads till it encounters one out of couple of bytes (space, newline and tab mainly).

I looked at the source for the library and I know what to do if I have access to the internal buffer used by bufio structs. Is there any way I could "monkey patch" the package and add another method or two to it? Or another way to get the functionality I need?

like image 447
Abhay Buch Avatar asked May 30 '12 11:05

Abhay Buch


2 Answers

Something along this approach (caution: untested code):

type reader struct{
        *bufio.Reader // 'reader' inherits all bufio.Reader methods
}

func newReader(rd io.Reader) reader {
        return reader{bufio.NewReader(rd)}
}

// Override bufio.Reader.ReadBytes
func (r reader) ReadBytes(delim byte) (line []byte, err error) {
        // here goes the monkey patch
}

// Or

// Add a new method to bufio.Reader
func (r reader) ReadBytesEx(delims []byte) (line []byte, err error) {
        // here goes the new code
}

EDIT: I should have noted that this doesn't help to access the original package internals (non exported entities). Thanks Abhay for pointing that out in your comment.

like image 163
zzzz Avatar answered Nov 01 '22 13:11

zzzz


It's usually best to solve problems using the package API. If you have a compelling reason to access unexported features though, copy the package source and hack it up. The BSD-style license as about as liberal as they come.

like image 43
Sonia Avatar answered Nov 01 '22 12:11

Sonia