“如果不支持ReadByte,将其包装在bufio.NewReader中”模式

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

"wrap it in a bufio.NewReader if it doesn't support ReadByte" pattern

问题

以下是一个Go库的片段。请问有人可以指出r.(byteReader)的重要性吗?对于一个初学者来说,语法的使用并不明显。byteReader是一个定义的接口,似乎不是io.Reader的成员。由于这似乎是一种巧妙的代码,有人可以提供一些见解吗?

作者提到了"如果不支持ReadByte,则将其包装在bufio.NewReader中"的模式。https://github.com/dave-andersen/deltagolomb/blob/master/deltagolomb.go

type byteReader interface {
    io.Reader
    ReadByte() (c byte, err error)
}

func makeReader(r io.Reader) byteReader {
    if rr, ok := r.(byteReader); ok {
        return rr
    }
    return bufio.NewReader(r)
}
英文:

Following is a snippet from one of the Go libs. Could anyone please point out the significance of r.(byteReader)? The syntax usage is not very obvious to a novice. byteReader is a defined interface and does not seem to be the member of io.Reader. Since, this seems to be some kind of nifty code, can anyone provide some insight.

The author mentions: "wrap it in a bufio.NewReader if it doesn't support ReadByte" pattern. https://github.com/dave-andersen/deltagolomb/blob/master/deltagolomb.go

type byteReader interface {
    io.Reader
    ReadByte() (c byte, err error)
}

func makeReader(r io.Reader) byteReader {
    if rr, ok := r.(byteReader); ok {
        return rr
    }
    return bufio.NewReader(r)
}

答案1

得分: 6

r.(byteReader)被称为类型断言。即使io.Reader本身没有实现byteReader接口,但存储在r中的值仍然有可能实现了byteReader接口。因此,通过进行类型断言,你可以确定是否满足这种情况:

规范中指出:

> x.(T)断言x不是nil,并且存储在x中的值是类型T。表示为x.(T)的符号被称为类型断言。
> ...
> 如果T是一个接口类型,x.(T)断言x的动态类型实现了接口T。

编辑

注释中的“将其包装在bufio.NewReader中”是指makeReader提供的io.Reader;如果它没有实现byteReadermakeReader将其包装在实现了byteReaderbufio.Reader中,并返回它。

英文:

r.(byteReader) is called a type assertion. Even if io.Reader doesn't implement the byteReader interface in itself, it it still possible that the value stored in r might implement byteReader. So, by doing the type assertion, you can assert if that is the case:

The specification states:

> x.(T) asserts that x is not nil and that the value stored in x is of
> type T. The notation x.(T) is called a type assertion.
> ...
> If T is
> an interface type, x.(T) asserts that the dynamic type of x implements
> the interface T.

Edit

The comment, "wrap it in a bufio.NewReader", refers to makeReader's provided io.Reader; if it doesn't implement byteReader, makeReader will wrap it in a bufio.Reader which does implement bytesReader, and return it instead.

huangapple
  • 本文由 发表于 2015年8月31日 14:33:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/32305176.html
匿名

发表评论

匿名网友

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

确定