【Go】interface


golang中的interface类型本质上是指针

  1. 实现多态

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    package main

    import "fmt"

    // interface本质是一个指针
    type Animal interface {
    Sleep()
    GetType() string
    GetColor() string
    }

    // Cat、Dog 子类实现接口中的全部方法
    type Cat struct {
    Type string
    Color string
    }
    type Dog struct {
    Type string
    Color string
    }

    func (this *Cat) Sleep() {
    fmt.Println("Cat is sleeping")
    }
    func (this *Dog) Sleep() {
    fmt.Println("Dog is sleeping")
    }
    func (this *Cat) GetType() string {
    return this.Type
    }
    func (this *Dog) GetType() string {
    return this.Type
    }
    func (this *Cat) GetColor() string {
    return this.Color
    }
    func (this *Dog) GetColor() string {
    return this.Color
    }

    // 多态-》父类变量(指针)指向子类变量(引用)
    func ShowAnimal(animal Animal) {
    animal.Sleep()
    fmt.Println("Type: ", animal.GetType())
    fmt.Println("Color: ", animal.GetColor())
    }

    func main() {

    // 子类对象
    cat := Cat{
    Type: "Cat",
    Color: "White",
    }
    dog := Dog{
    Type: "Dog",
    Color: "Yellow",
    }

    //
    ShowAnimal(&cat)
    ShowAnimal(&dog)
    }

    测试结果

  2. 万能接口interface{},所有基本数据类型包括struct都实现了它(类似Java中的Object),因此可以用来接参并实现反射

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    package main

    import "fmt"

    // 空接口也称为万能接口,基本数据类型如int、string、float、struct等都实现了它
    func myFunc(arg interface{}) {
    fmt.Println("myFunc is used...")
    fmt.Println("arg is ", arg)

    // 断言机制
    value, ok := arg.(int) // 判断接到的参数类型是否为int
    if ok {
    fmt.Println("arg type is int and", "value is ", value)
    } else {
    fmt.Println("arg is not int and", "value is ", value)
    }

    }

    type Man struct {
    name string
    }

    func main() {
    // 引用任意数据类型
    myFunc(1)
    myFunc("111")
    myFunc("1.11")
    myFunc(Man{"cx"})
    }

    测试结果