interface

作者: cc程cc | 来源:发表于2022-04-07 08:30 被阅读0次

    (1)在go里面interface的出现更像是一种多态的模式
    声明了interface,声明了方法
    其他对象就可以实现自己的对应的方法了。
    比如:
    type people interface {
    color() string
    }

    type man struct{
    }
    type woman struct {
    }

    fun(m man)color() string
    {
    return "红色"
    }

    fun(w woman)color() string
    {
    return "黑色"
    }

    在main函数中使用
    {
    //声明两个接口
    var p1,p2 people
    w := woman{}
    m := man{}
    p1 = w
    p2 = m
    p1.color()
    p2.color()

    //p1执行womanman中的color函数
    //p2执行man中的color函数

    PS: w,ok := p1.(*woman)//判断p1是否是woman类型的数据.

    }

    相关文章

      网友评论

          本文标题:interface

          本文链接:https://www.haomeiwen.com/subject/sfhzbktx.html