英文:
"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
;如果它没有实现byteReader
,makeReader
将其包装在实现了byteReader
的bufio.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论