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

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!\n")
}

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

type Pig struct {
    Id int
}

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

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

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

}

  

上一篇:[Java] 泛型Generic


下一篇:运算