go语言 判断一个实例是否实现了某个接口interface

go代码:

package main

import "fmt"

type Animal interface {
    run()
    walk()
}

type Dog struct {
    Id int
}

func (dog Dog) run()  {
    fmt.Printf("I am Dog,I can Run!
")
}

func (dog Dog) walk(){
    fmt.Printf("I am Dog,I can walk!
")
}

type Pig struct {
    Id int
}

func (pig Pig) run()  {
    fmt.Printf("I am Pig,I can Run!
")
}

func main() {
    dog := Dog{100}
    var animal0 interface{} = dog
    if _, ok := animal0.(Animal); ok {
        fmt.Printf("animal0 implement Animal interface!
")
    }else {
        fmt.Printf("animal0 not implement Animal interface!
")
    }

    pig:=Pig{18}
    var animal1 interface{} = pig
    if _, ok := animal1.(Animal); ok {
        fmt.Printf("animal1 implement Animal interface!
")
    }else {
        fmt.Printf("animal1 not implement Animal interface!
")
    }

}

结果:

animal0 implement Animal interface!
animal1 not implement Animal interface!
原文地址:https://www.cnblogs.com/iuyy/p/14110727.html