接口的值的类型

接口变量内部是存储的类型和值的指针,所以并不用是用接口的指针
接口变量也是值传递
指针接受者只能以指针方式使用,值接受者都可以

go 中 取接口的类型有两种方式

  1. switch

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    func (dl Downloader) {
    switch v := dl.(type) {
    case *interfaces.SimpleDownload:
    fmt.Println("sim:", v)
    case *interfaces.RealDownload:
    fmt.Println("real:", v)
    }
    }

    var dl Downloader
    dl = &interfaces.SimpleDownload{}
    inspect(dl)
    dl = &interfaces.RealDownload{}
    inspect(dl)

    sim: &{}
    real: &{}
    */
  2. 一种是type assertion 或者另外一种叫法是 comma-ok

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var dl Downloader
    dl = &interfaces.SimpleDownload{}
    if _ ,ok := dl.(*interfaces.SimpleDownload); ok {
    fmt.Println("SimpleDownload")
    }
    dl = &interfaces.RealDownload{}
    if _ ,ok := dl.(*interfaces.RealDownload); ok {
    fmt.Println("RealDownload")
    }

    SimpleDownload
    RealDownload
    */