dongshi4589 2015-10-29 03:16
浏览 159
已采纳

golang的zlib / reader.go文件中的“ r。(flate.Reader)”是什么意思?

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

  • 写回答

1条回答 默认 最新

  • douxi3977 2015-10-29 04:09
    关注

    The Go Programming Language Specification

    Type assertions

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?