多态函数

// 多态
// 示例
package main

import (
	"fmt"
)
type notifier interface {
    notify()
}
type user struct{
    name string
    email string
}
func (u *user) notify(){
    fmt.Printf("Sending user email to %s<%s>\n", u.name, u.email)
}
type admin struct{
    name string
    email string
}
func (a *admin) notify(){
    fmt.Printf("Sending admin email to %s<%s>\n", a.name, a.email)
}
// 多态函数,不同实例类型调用相同方法返回不同实例的结果
func sendNotification(n notifier){
    n.notify()
}

func main(){
    bill := user{"Bill", "bill@email.com"}
    sendNotification(&bill) // 传地址
    
    lisa := admin{"Lisa", "lisa@email.com"}
    sendNotification(&lisa) // 传地址
}
posted @ 2021-10-29 15:21  我在路上回头看  阅读(59)  评论(0编辑  收藏  举报