go语言学习笔记:接口查询与类型查询

有时候我们并不确定某个变量是否实现是某种接口,这会导致我们在代码中不敢使用它的某些功能。但是go语言可以让我们在运行时确定的类型。

总结一下就是go语言可以使用value.(SomeType)这样的方式来判断它是否是某种类型。 使用value.(type)这样的方式来获取它的类型:

package main

import (
    "fmt"
)

type bird interface{
    Fly()
    Sing()
}


type eagle struct {

}

func (e *eagle) Fly() {
    fmt.Println("eagle fly")
}

func (e *eagle) Sing() {
    fmt.Println("eagle sing")
}

type Human interface{
    // Fly()
    Sing()
}

type animal interface{
    Fly()
    Sing()
}

type anything struct{                      //定义一个anything的结构体

}

func (a anything) Sing() {
    fmt.Println("i am anything sing")
}

func (a anything) Fly(){
    fmt.Println("i am anything fly")
}

func main(){
    e :=eagle{}
    var b bird
    b = &e

    if _,ok := b.(Human); ok {              //注意绝对不要漏掉“.”
        fmt.Println("eagle is human")
    }

    if _,ok := b.(*Human); ok {             //这个编译不过,因为我们没有定义*Human的接口
        fmt.Println("eagle is *human")
    }

    if _,ok :=b.(animal); ok {              //虽然名字不一样,但eagle实现了Sing与Fly,那他也可以认为是一种animal类。实际上animal类与bird类在这个例子中是一样的东西。
        fmt.Println("eagle is animal")
    }

    if _,ok := b.(anything); ok {           //可以这么写,但是它不是anything,他们是不同的类型
        fmt.Println("eagle is anything")    
    }

    if _,ok := b.(*eagle); ok {             //这里返回true,注意,它是*eagle类型,而不是eagle类型。这个跟上面接口的查询方法是不一样的。
        fmt.Println("eagle is eagle")
    }

}

打印:
eagle is human
eagle is animal

eagle is eagle

func sqlQuote(x interface{}) string {  //这里的interface类型表明可以传入任意类型的变量,不要漏掉后面的{}。说明他是C语言中的void类型
    switch x := x.(type) {             //注意这里的关键字type和“.”,表示获取它的类型
    case nil:
        return "NULL"
    case int, uint:
        return fmt.Sprintf("%d", x) // x has type interface{} here.
    case bool:
        if x {
            return "TRUE"
        }
        return "FALSE"
    case string:
        return sqlQuoteString(x) // (not shown)
    default:
        panic(fmt.Sprintf("unexpected type %T: %v", x, x))
    }
}

 

posted @ 2017-12-01 11:20  你的KPI完成了吗  阅读(249)  评论(0)    收藏  举报