I found lots of code snippets like r.(flate.Reader)
in golang's zlib/reader.go file. What does it mean?
https://golang.org/src/compress/zlib/reader.go
func (z *reader) Reset(r io.Reader, dict []byte) error {
if fr, ok := r.(flate.Reader); ok {
z.r = fr
} else {
z.r = bufio.NewReader(r)
}
// more code omitted ...
}
P.S. source code of io
and flate
.
io: https://golang.org/src/io/io.go
flate: https://golang.org/src/compress/flate/inflate.go
The Go Programming Language Specification
For an expression x of interface type and a type T, the primary expression
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.
A type assertion used in an assignment or initialization of the special form
v, ok = x.(T) v, ok := x.(T) var v, ok = x.(T)
yields an additional untyped boolean value. The value of ok is true if the assertion holds. Otherwise it is false and the value of v is the zero value for type T. No run-time panic occurs in this case. C
r.(flate.Reader)
is a type assertion. For example,
func (z *reader) Reset(r io.Reader, dict []byte) error {
if fr, ok := r.(flate.Reader); ok {
z.r = fr
} else {
z.r = bufio.NewReader(r)
}
// more code omitted ...
}
r
is type io.Reader
, an interface
. fr, ok := r.(flate.Reader)
checks r
to see if it contains an io.Reader
of type flate.Reader
.