• golang interface 多态


    原文链接:http://www.52bd.net/code/210.html

    demo:

    package main
    
    import (
        "fmt"
    )
    //通知行为的接口
    type notifier interface{
        notify()
    }
    
    //自定义的用户类型
    type user struct{
        name string
        email string 
    }
    //notify是用指针接收者实现的方法
    func (u *user ) notify(){
        fmt.Println("用户:",u)
    }
    
    //自定义的管理员类型
    type admin struct{
        name string
        email string 
    }
    //notify是用指针接收者实现的方法
    func (u *admin ) notify(){
        fmt.Println("管理员:",u)
    }
    
    //sendNotification 接受一个实现了notifier接口的值
    func sendNotification(n notifier){
        n.notify()
    }
    
    func main(){
        user := user{"lp","344085057@qq.com"}
        sendNotification(&user)
    
        admin := admin{"admin","344085057@qq.com"}
        sendNotification(&admin)
    }

    运行结果:

    [root@golang]# go run interface.go 
    用户: &{lp 344085057@qq.com}
    管理员: &{admin 344085057@qq.com}
  • 相关阅读:
    每日日报1
    shazidouhui的使用体验
    水滴的使用体验
    麻雀记的使用体验
    钢镚儿的使用体验
    TD课程通的使用体验
    01 fs模块
    0 mysql 安装
    slot
    vue引入 lodash
  • 原文地址:https://www.cnblogs.com/wangjq19920210/p/13066524.html
Copyright © 2020-2023  润新知