go - "wrap it in a bufio.NewReader if it doesn't support ReadByte" pattern -
this question has answer here:
- what “foo.(bar.baz)” thing in go code? 2 answers
following snippet 1 of go libs. please point out significance of r.(bytereader)
? syntax usage not obvious novice. bytereader
defined interface , not seem member of io.reader
. since, seems kind of nifty code, can provide insight.
the author mentions: "wrap in bufio.newreader if 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) }
r.(bytereader)
called type assertion. if io.reader
doesn't implement bytereader
interface in itself, it still possible value stored in r
might implement bytereader
. so, doing type assertion, can assert if case:
the specification states:
x.(t) asserts x not nil , value stored in x of type t. notation x.(t) called type assertion.
...
if t interface type, x.(t) asserts dynamic type of x implements interface t.
edit
the comment, "wrap in bufio.newreader", refers makereader
's provided io.reader
; if doesn't implement bytereader
, makereader
wrap in bufio.reader
implement bytesreader
, , return instead.
Comments
Post a Comment