向现有(标准)类型添加一个新方法

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

Adding a new method to an existing (standard) type

问题

我正在编写一些代码,需要使用bufio包中的ReadBytes方法提供的功能。具体来说,该方法从Reader中读取,直到遇到特定的字节。我需要的是读取到遇到其中一个字节(主要是空格、换行和制表符)为止。

我查看了该库的源代码,如果我可以访问bufio结构体使用的内部缓冲区,我知道该怎么做。是否有办法“猴子补丁”该包并添加另一个或两个方法?或者有其他方法可以获得我所需的功能?

英文:

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?

答案1

得分: 5

type reader struct{
*bufio.Reader // 'reader'继承了所有bufio.Reader的方法
}

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

// 重写bufio.Reader.ReadBytes
func (r reader) ReadBytes(delim byte) (line []byte, err error) {
// 这里是猴子补丁
}

// 或者

// 给bufio.Reader添加一个新的方法
func (r reader) ReadBytesEx(delims []byte) (line []byte, err error) {
// 这里是新的代码
}

编辑:我应该注意到这个方法不能访问原始包的内部(非导出实体)。感谢Abhay在评论中指出这一点。

英文:

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.

答案2

得分: 1

通常最好使用软件包API来解决问题。但如果你有充分的理由需要访问未导出的功能,可以复制软件包源代码并进行修改。BSD风格的许可证非常自由。

英文:

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.

huangapple
  • 本文由 发表于 2012年5月30日 19:27:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/10815367.html
匿名

发表评论

匿名网友

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

确定