Adding a new method to an existing (standard) type

I am writing code that needs functionality that is almost satisfied by the method ReadBytesin the package bufio. In particular, this method reads from Readeruntil it encounters a specific byte. I need something that is read until it meets one of the two bytes (space, new line and tab basically).

I looked at the source of the library and I know what to do if I have access to the internal buffer used by bufiostructs. Is there a way that I could "decapitate the patch" of a package and add another or two methods to it? Or another way to get the functionality I need?

+6
source share
2 answers

Something like 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 noticed that this does not help to access the source inner packages (not exported objects). Thank you Abhai for pointing this out in your comment.

+5
source

It's usually best to solve problems using the package API. If you have a good reason to access unexcited features, copy the package source and crack it. The BSD type license is just as liberal as they are.

+1
source

All Articles