• 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!
  • 相关阅读:
    CSS三大特性
    CSS选择器
    CSS(1)
    多媒体标签
    快捷键
    H5注意点(2)
    H5注意点(1)
    List详解
    求最大子串和以及其中一个子串(java)
    隧道项目
  • 原文地址:https://www.cnblogs.com/iuyy/p/14110727.html
Copyright © 2020-2023  润新知